Filtering based on .count() of a forgein key field in Django querysets

别来无恙 提交于 2019-12-10 18:38:11

问题


So I have some Django 1.3 models like this:

class Type(models.Model):
  is_bulk = models.BooleanField()

class Component(models.Model):
  parent = models.ForeignKey(Type)

Some Type's have 0 Component's, some have 1, or 2, etc. How do I write a QuerySet that filters all Type's that have > 0 Components. i.e. exclude Types that have 0 Components?


回答1:


from django.db.models import Count
Type.objects.annotate(component_count=Count('component')).exclude(component_count=0)


来源:https://stackoverflow.com/questions/8068771/filtering-based-on-count-of-a-forgein-key-field-in-django-querysets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!