Skip to content

Commit bc0467e

Browse files
ertglsarahboyce
andcommitted
Add migration that links individual members to users by email
Co-authored-by: Sarah Boyce <[email protected]>
1 parent 84c0826 commit bc0467e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Generated by Django 5.2.7 on 2025-10-21 23:53
2+
3+
from django.conf import settings
4+
from django.db import migrations, transaction
5+
6+
7+
def link_individual_members_to_users_by_email(apps, schema_editor):
8+
# These models aren't the ones imported from the `models.py` files.
9+
# They're fake, and constructed based on the historical migrations.
10+
# Ensure that the `Migration.dependencies` contains the migrations needed to
11+
# construct the models that are used here.
12+
IndividualMember = apps.get_model("members.IndividualMember")
13+
User = apps.get_model(settings.AUTH_USER_MODEL)
14+
15+
individual_members_queryset = IndividualMember.objects.filter(
16+
user_id__isnull=True,
17+
).select_for_update(
18+
nowait=False,
19+
)
20+
users_queryset = User.objects.filter(
21+
email__in=individual_members_queryset.values_list("email", flat=True),
22+
)
23+
for user in users_queryset.iterator():
24+
with transaction.atomic():
25+
IndividualMember.objects.filter(email=user.email).update(user=user)
26+
27+
28+
def noop(apps, schema_editor):
29+
pass
30+
31+
32+
class Migration(migrations.Migration):
33+
34+
dependencies = [
35+
("auth", "0012_alter_user_first_name_max_length"),
36+
("members", "0011_alter_individualmember_options_and_more"),
37+
]
38+
39+
operations = [
40+
migrations.RunPython(
41+
link_individual_members_to_users_by_email,
42+
# Don't raise `django.db.migrations.exceptions.IrreversibleError`
43+
# when reverting to an older migration.
44+
reverse_code=noop,
45+
),
46+
]

0 commit comments

Comments
 (0)