[Fixed]-Django foreign key count filter

0πŸ‘

βœ…

So after trying a lot, this was a solution that worked:

Bar.objects.values("foo_id").annotate(Count("foo_id")).filter(pk__count__gt=1)

Not exactly sure why this worked and the other didn’t, but it essentially just gets the count of Bar objects with the same foo_id and makes sure there is more than 1.

If somebody would like to explain a potential reason why this works and the other did not, that would be appreciated.

πŸ‘€Ryan Saxe

1πŸ‘

I had the same issue by import mistake. This is solution for my use case

# from django.db.models.sql.aggregates import Count  # wrong import
from django.db.models import Count   # correct one
πŸ‘€mnach

0πŸ‘

There can be multiple reasons for this error, I’ll try to tell the probable causes:

  1. Recently upgrading your django version may cause the problem, clear
    migrations, rerun.
  2. Moving from local server to production server can cause this problem
    sometimes.
  3. Your app name can cause the problem, if it starts with β€œ__”.
  4. Try other simpler queries, if they work, try to change the query so
    that you don’t use the num_model.
  5. also check if you can get the count of them ( the dirty way πŸ™‚ ):

    for foo in Foo.objects.all():
    if foo.bar_set.count() < 2:
    #do sth like : foo.bar_set.get() or temp = temp + 1

as of your short description of model (not your main code), cannot find other causes. Your query should work.

πŸ‘€P3zhman

Leave a comment