Brenden
Brenden

Reputation: 8764

Exclude count of annotate items in Django Query

I am querying the DB to get a list of objects, and using annotate() to count how many associated Items they have with it.

I'd like to only return objects with an associated item count above 5.

lists = List.objects.exclude(picture_url='').exclude(picture_url__icontains='google').select_related('city','city__country', 'user', 'user__profile').annotate(items_added=Count('item'))[:10]

Upvotes: 2

Views: 1164

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174622

lists = List.objects.exclude(picture_url='') \
        .exclude(picture_url__icontains='google') \
        .select_related('city','city__country', 'user', 'user__profile') \
        .annotate(items_added=Count('item')) \
        .filter(items_added__gt=5)[:10]

Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet; this QuerySet can be modified using any other QuerySet operation, including filter(), order_by, or even additional calls to annotate().

Upvotes: 4

Related Questions