计算多对多关系的属性并按其过滤

时间:2015-10-14 05:07:32

标签: django django-models

我想做一些与this略有不同的事情。

假设我的models.py中有类似的东西:

class Hipster(models.Model):
  name = CharField(max_length=50)
  has_iphone = BooleanField(default=True)

class Party(models.Model):
  participants = models.ManyToManyField(Hipster, related_name="participants")

然后做:

hip_parties = Party.objects.filter(participants__has_iphone__istrue__count=4)

我该怎么做?

更新:

>>> Question.objects.filter(options__is_correct=True).annotate(options__count=Count('options')).filter(options__count=0)
[]
>>> q = Question.objects.get(id=49835)
>>> q.options.all()[0].is_correct
False
>>> q.options.all()[1].is_correct
False
>>> q.options.all()[2].is_correct
False
>>> q.options.all()[3].is_correct
False
>>> q.options.all()[4].is_correct
False
>>> q.options.all()[5].is_correct
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/patrickbassut/Programming/logus/lib/python2.7/site-packages/django/db/models/query.py", line 177, in __getitem__
    return list(qs)[0]
IndexError: list index out of range

1 个答案:

答案 0 :(得分:1)

您可以为此使用注释。

from django.db.models import Count
Party.objects.filter(
    participants__has_iphone=True
).annotate(iphone_count=Count('participants')).filter(
    iphone_count=4
)