问题
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