【发布时间】:2016-01-13 21:33:06
【问题描述】:
假设有这样的结构:
PARTICIPATION_STATUSES = (
(0, 'No, thanks'),
(1, 'I may attend'),
(2, 'I\'ll be there'),
)
class Model1(models.Model):
# ...
class Model2(models.Model):
status = models.PositiveIntegerField(
_('participation status'), choices=PARTICIPATION_STATUSES)
field = models.ForeignKey(Model1, related_name='model1_participation')
我想要做的是用Model2 对象的计数来注释Model1 的每个对象,其中状态等于特定值(状态编号是这个特定的示例)。
在我的伪代码中它看起来像:
queryset = Model1.objects.all()
queryset.annotate(declined=Count('model1_participation__status=0'))
queryset.annotate(not_sure=Count('model1_participation__status=1'))
queryset.annotate(accepted=Count('model1_participation__status=2'))
但我不能以这种方式注释查询集,因为 Django 无法解析 status=<n>。
什么是实现我想要的正确方法?
【问题讨论】:
标签: python django django-models