From a3a8c305acc6daa6dd224e3bad2d646c62243227 Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Sat, 26 Aug 2023 20:18:23 -0400 Subject: [PATCH] membershipworks: Use EXISTS for testing flags in `is_active` This behaves much more correctly, although may not have ideal performance --- membershipworks/models.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/membershipworks/models.py b/membershipworks/models.py index d4968ec..04907fc 100644 --- a/membershipworks/models.py +++ b/membershipworks/models.py @@ -3,7 +3,7 @@ from typing import Optional import django.core.mail.message from django.conf import settings from django.db import models -from django.db.models import Q, Count, BooleanField +from django.db.models import Exists, OuterRef class Flag(models.Model): @@ -21,14 +21,17 @@ class Flag(models.Model): class MemberQuerySet(models.QuerySet): + # TODO: maybe rename to reflect EXISTS? @staticmethod def has_flag(flag_type: str, flag_name: str): - return Count( - "uid", - filter=Q(flags__name=flag_name, flags__type=flag_type), - output_field=BooleanField(), - ) + return Exists(Flag.objects.filter( + type=flag_type, + name=flag_name, + members=OuterRef("pk") + )) + # TODO: it should be fairly easy to reduce the number of EXISTS by + # merging the ORed flags def with_is_active(self): return self.annotate( is_active=(