Django models - how to filter number of ForeignKey objects

后端 未结 4 1633
死守一世寂寞
死守一世寂寞 2020-12-23 19:27

I have a models A and B, that are like this:

class A(models.Model):
  title = models.CharField(max_length=20)
  (...)

class B(mode         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 20:19

    The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for "django filter foreign key count" I'd like to add an easier solution with a recent django version using Aggregation.

    from django.db.models import Count
    cats = A.objects.annotate(num_b=Count('b')).filter(num_b__lt=2)
    

    In my case I had to take this concept a step further. My "B" object had a boolean field called is_available, and I only wanted to return A objects who had more than 0 B objects with is_available set to True.

    A.objects.filter(B__is_available=True).annotate(num_b=Count('b')).filter(num_b__gt=0).order_by('-num_items')
    

提交回复
热议问题