PERF(promotions): batch allowed-user lookup in get_configured_promotion_amount
Checking each recipient via Recipient.is_user_allowed() inside the loop issued one AllowedUser query per restricted recipient (N+1). Fetch all matching AllowedUser rows for the plan's recipients in a single query up front instead. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
ac37f15bea
commit
33aa0ed1b4
1 changed files with 9 additions and 2 deletions
|
|
@ -136,9 +136,16 @@ class Plan(BaseModel):
|
||||||
return self.title
|
return self.title
|
||||||
|
|
||||||
def get_configured_promotion_amount(self, user_uuid=None):
|
def get_configured_promotion_amount(self, user_uuid=None):
|
||||||
|
recipients = list(self.recipients.filter(recipient_uuid_field='->event:user')) #TODO: instead of hard code use better soloution
|
||||||
|
restricted_ids = [r.pk for r in recipients if r.access_type == RecipientTypeChoices.RESTRICTED]
|
||||||
|
allowed_ids = set(
|
||||||
|
AllowedUser.objects.filter(recipient_id__in=restricted_ids, user__uuid=user_uuid)
|
||||||
|
.values_list('recipient_id', flat=True)
|
||||||
|
) if restricted_ids and user_uuid else set()
|
||||||
|
|
||||||
amount = 0
|
amount = 0
|
||||||
for recipient in self.recipients.filter(recipient_uuid_field='->event:user'): #TODO: instead of hard code use better soloution
|
for recipient in recipients:
|
||||||
if not recipient.is_user_allowed(user_uuid):
|
if recipient.access_type == RecipientTypeChoices.RESTRICTED and recipient.pk not in allowed_ids:
|
||||||
continue
|
continue
|
||||||
base_amount, promotion_amount = recipient.get_promotion_amount()
|
base_amount, promotion_amount = recipient.get_promotion_amount()
|
||||||
amount += promotion_amount
|
amount += promotion_amount
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue