henriquebastos / django-aggregate-if

Conditional aggregates for Django queries, just like the famous SumIf and CountIf in Excel.
MIT License
138 stars 17 forks source link

Automatically modify Q expression to prepend the aggregated thing #12

Open mbertheau opened 9 years ago

mbertheau commented 9 years ago

My uses of Count(.., only=..) all look like this:

q_not_expired = Q(...)
products_not_expired = Product.objects.filter(q_not_expired)
qs.annotate(num_published_orders=Count('partner__stockrecords__product',
                                       only=Q(partner__stockrecords__product__in=products_not_expired)))
qs.annotate(registered_participants=Count(
                    'participant', only=Q(participant__status=Participant.REGISTERED)))

So I'm wondering whether it'd make sense to make aggregate-if work such that you can write this instead:

qs.annotate(num_published_orders=Count('partner__stockrecords__product',
                                       only=q_not_expired))
qs.annotate(registered_participants=Count('participant',
                                          only=Q(status=Participant.REGISTERED)))

That way if you have Q-expressions prepared somewhere they can be easily plugged in here.

henriquebastos commented 9 years ago

Can you send me a PR with a failing regression test?