Repository navigation
Expand file tree
/
Copy path0011_normalizing_lead_email.py
More file actions
53 lines (45 loc) · 1.7 KB
/
Copy path0011_normalizing_lead_email.py
File metadata and controls
53 lines (45 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Generated by Django 3.0.3 on 2020-02-28 11:30
from itertools import count
from django.db import IntegrityError, migrations
from django.db.transaction import atomic
def normalize_email(apps, schema_editor):
'''
We can't import the Post model directly as it may be a newer
version than this migration expects. We use the historical version.
'''
User = apps.get_model('core', 'User')
print()
for msg in normalize_all_user_leads_emails(User):
print(msg)
def normalize_all_user_leads_emails(User):
"""
Migrate all lead email to lower case with prefix excluded
:param User:
:return:
"""
no_migrate_groups = {'member', 'client'}
for user in User.objects.order_by('id').all():
original_email = user.email
normalized_email = user.email.lower()
if normalized_email != original_email:
user_groups = {g.name for g in user.groups.all()}
if no_migrate_groups.isdisjoint(user_groups):
for exclusion_index in count(1):
user.email = f'excluded{exclusion_index}.{normalized_email}'
with atomic():
try:
user.save()
except IntegrityError:
pass
else:
break
else:
user_groups_str = ','.join(user_groups)
yield f'User groups {user_groups_str} user {user.id}, {user.email}'
class Migration(migrations.Migration):
dependencies = [
('core', '0010_normalizing_email'),
]
operations = [
migrations.RunPython(normalize_email, migrations.RunPython.noop)
]