Merge pull request #1121 from ae-utbm/fix-sales

Fix counter selection performance on SellingForm
This commit is contained in:
thomas girod 2025-06-13 13:58:38 +02:00 committed by GitHub
commit 9d841cd606
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

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
) )