-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a migration to ensure EmailAddress model populated
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
1 parent
3d77400
commit 10f0e77
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
itou/users/migrations/0015_ensure_emailaddress_model_use.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
), | ||
] |