fix: counter selection queryset performance on SellingForm

This commit is contained in:
imperosol 2025-06-12 14:35:39 +02:00
parent 9c8e3b7cac
commit c62c09f603

View File

@ -163,15 +163,16 @@ class SellingsForm(forms.Form):
def __init__(self, club, *args, **kwargs): def __init__(self, club, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
counters_qs = ( # postgres struggles really hard with a single query having three WHERE conditions,
Counter.objects.filter( # but deals perfectly fine with UNION of multiple queryset with their own WHERE clause,
Q(club=club) # so we do this to get the ids, which we use to build another queryset that can be used by django.
| Q(products__club=club) club_sales_subquery = Selling.objects.filter(counter=OuterRef("pk"), club=club)
| Exists(Selling.objects.filter(counter=OuterRef("pk"), club=club)) ids = (
) Counter.objects.filter(Q(club=club) | Q(products__club=club))
.distinct() .union(Counter.objects.filter(Exists(club_sales_subquery)))
.order_by(Lower("name")) .values_list("id", flat=True)
) )
counters_qs = Counter.objects.filter(id__in=ids).order_by(Lower("name"))
self.fields["counters"] = forms.ModelMultipleChoiceField( self.fields["counters"] = forms.ModelMultipleChoiceField(
counters_qs, label=_("Counter"), required=False counters_qs, label=_("Counter"), required=False
) )