1

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?

benwad
  • 6,414
  • 10
  • 59
  • 93
  • `count` is field of your model ? – Priyank Patel Mar 04 '14 at 11:17
  • No, I was using it in the way that you'd use `objQuerySet.count()` on a query set. – benwad Mar 04 '14 at 11:18
  • There is no `__count` [field lookup](https://docs.djangoproject.com/en/1.6/ref/models/querysets/#field-lookups) in Django querysets – lanzz Mar 04 '14 at 11:31
  • I was wondering how I could get the functionality described in my question - to be able to filter by the number of objects in a foreign key relation. My inclusion of `__count` was just a guess, and I posted it here to demonstrate what I was trying to do. – benwad Mar 04 '14 at 11:42

1 Answers1

3

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • For some reason it's telling me that `links_by_source` is not defined. – benwad Mar 04 '14 at 12:41
  • Ah - it turns out that the relation name needs to be passed as a string. I'll accept your post but can't seem to make such a small edit to it - could you edit it so links_by_source is a string? – benwad Mar 04 '14 at 12:54