注释附加到特定对象的django-taggit标记

时间:2012-08-23 00:49:26

标签: mysql django django-queryset django-taggit

我有一个使用django-taggit标记的对象。如果我想获得附加到该对象的所有标签的列表,我会遵循这样的文档:

apple = Food.objects.create(name="apple")
apple.tags.add("red", "green", "delicious")
apple.tags.all()

如果我想知道现有的每个标签附加了多少个Food对象,我会执行以下操作:

Tag.objects.all().annotate(food_count=Count('food'))

如果我想计算所有附加 附加到'apple'的标签的食物项目,我可以执行以下操作:

apple = Food.objects.create(name="apple")
apple.tags.add("red", "green", "delicious")
apple.tags.all().annotate(food_count=Count('food'))

好的,我的问题也是如此。假设我的食物模型有一个标志字段:

class Food(models.Model):
    name = models.CharField(max_length=200, unique = True)
    healthy_flag = models.BooleanField(default=False)

如何计算所有健康食物的附加附加到'apple'的标签(其中健康食品由healthy_flag表示) = 1)?基本上,对于每个“苹果”标签,有多少健康食品共享这个标签?

1 个答案:

答案 0 :(得分:1)

找到答案here

apple.tags.all().annotate(food_count=Count('food')).filter(food__health_flag = True)