Skip to content

Commit 84c0826

Browse files
committed
Add management command link_individual_members_to_users_by_email
1 parent 20117b6 commit 84c0826

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from django.core.management.base import BaseCommand
2+
from django.db import transaction
3+
4+
from ...models import IndividualMember
5+
6+
7+
class Command(BaseCommand):
8+
def add_arguments(self, parser):
9+
parser.add_argument(
10+
"--no-logging",
11+
action="store_true",
12+
help="Disable writing number of updated records to stdout.",
13+
)
14+
15+
def handle(self, *args, **options):
16+
with transaction.atomic():
17+
count = IndividualMember.match_and_set_users_by_email()
18+
if not options["no_logging"]:
19+
self.stdout.write(f"Updated: {count}")

members/models.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from enum import StrEnum
33

44
from django.conf import settings
5+
from django.contrib.auth import get_user_model
56
from django.core import signing
67
from django.core.mail import send_mail
78
from django.db import models, transaction
@@ -17,6 +18,9 @@
1718

1819
from djangoproject.thumbnails import LogoThumbnailMixin
1920

21+
User = get_user_model()
22+
23+
2024
BRONZE_MEMBERSHIP = 1
2125
SILVER_MEMBERSHIP = 2
2226
GOLD_MEMBERSHIP = 3
@@ -83,6 +87,22 @@ class Meta:
8387
),
8488
]
8589

90+
@classmethod
91+
def match_and_set_users_by_email(cls, queryset=None):
92+
updated_count = 0
93+
if queryset is None:
94+
queryset = cls.objects.all()
95+
queryset = queryset.filter(user_id__isnull=True)
96+
# Wait for other active transactions to prevent race conditions.
97+
queryset = queryset.select_for_update(nowait=False)
98+
users_queryset = User.objects.filter(
99+
email__in=queryset.values_list("email", flat=True),
100+
)
101+
for user in users_queryset.iterator():
102+
with transaction.atomic():
103+
updated_count += cls.objects.filter(email=user.email).update(user=user)
104+
return updated_count
105+
86106
@classmethod
87107
def send_account_invite_mails(cls, queryset):
88108
results = {}

0 commit comments

Comments
 (0)