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=(