Search code examples
djangodjango-querysetdjango-related-manager

Filtering QuerySet by __count of RelatedManager


I've got a QuerySet I'd like to filter by the count of a related_name. Currently I've got something like this:

objResults = myObjects.filter(Q(links_by_source__status=ACCEPTED),Q(links_by_source__count=1))

However, when I run this I get the following error message:

Cannot resolve keyword 'count' into field

I'm guessing that this query is operating individually on each of the links_by_source connections, therefore there is no count function since it's not a QuerySet I'm working with. Is there a way of filtering so that, for each object returned, the number of links_by_source is exactly 1?


Solution

  • You need to use an aggregation function to get the count before you can filter on it.

    from django.db.models import Count
    myObjects.filter(
      links_by_source__status=ACCEPTED).annotate(link_count=Count('links_by_source')
    ).filter(link_count=1)
    

    Note, you should pay attention to the order of the annotate and filter here: that query counts the number of ACCEPTED links, not sure if you want that or you want to check that the total count of all links is 1.