Skip to content

Commit

Permalink
Add a migration to ensure EmailAddress model populated
Browse files Browse the repository at this point in the history
Many users on production have User.email set with no corresponding email address model

Fix migration should assume emails are not verified

Fix migration typo
  • Loading branch information
calummackervoy committed Nov 26, 2024
1 parent 3d77400 commit 10f0e77
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions itou/users/migrations/0015_ensure_emailaddress_model_use.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from django.db import migrations
from django.db.models import OuterRef, Subquery


def create_email_addresses_for_users(apps, schema_editor):
User = apps.get_model("users", "User")
EmailAddress = apps.get_model("account", "EmailAddress")

# Get all those values of User.email where there is no corresponding EmailAddresses instance
users_missing_addresses = (
User.objects.prefetch_related("emailaddress_set")
.annotate(email_exists=Subquery(EmailAddress.objects.filter(email=OuterRef("email")).values("id")[:1]))
.filter(email_exists__isnull=True)
.values("id", "email")
)

EmailAddress.objects.bulk_create(
EmailAddress(user_id=x["id"], email=x["email"], primary=True, verified=False) for x in users_missing_addresses
)


class Migration(migrations.Migration):
"""
This migration was created at a time when not all User email addresses had an associated EmailAddress.
It ensures that EmailAddress instances are created where they are not existing.
Of course this means that the migration can be squashed later.
"""

dependencies = [
("users", "0014_alter_jobseekerprofile_birthdate__add_index"),
]

operations = [
migrations.RunPython(
create_email_addresses_for_users,
reverse_code=migrations.RunPython.noop,
),
]

0 comments on commit 10f0e77

Please sign in to comment.