MOntu
MOntu

Reputation: 1047

Django group by yield wrong result after filtering by annotated field

So, I mainly want to group by my result by a certain field which I know I can do like

ModelName.objects.values('somefield').annotate(freq=Count('somefield'))

But before that, I want to filter based on one annotated field, but this yields the wrong result, I tried,

# Works fine
filtered_queryset = ModelName.objects.annotate(c=Count('related_field')).filter(c__gt=0)
# Yields wrong result.
filtered_queryset.values('somefield').annotate(freq=Count('somefield')) 

I tried passing distinct=True but this didn't solve my problem. Why am I missing here?

Upvotes: 1

Views: 224

Answers (1)

Simon Charette
Simon Charette

Reputation: 5116

Do you happen to have a defined ModelName.Meta.ordering by any chance?

If that's the case then you'll want to order_by() to clear it out else the referenced columns will be included in the GROUP BY clause as well.

This is a common footgun by the way and will be getting warned about in Django 2.2 and removed in Django 3.1.

Upvotes: 1

Related Questions