Question

I have an object that is tagged using django-taggit. If I wanted to get a list of all the tags attached to this object, I would follow the documentation like so:

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

If I wanted to know how many Food objects were attached to each tag in existence, I would do the following:

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

If I wanted to get a count of all of the food items attached only to the tags that are attached to 'apple', I could do the following:

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

Ok, so for my question. Let's say my Food model has a field with a flag:

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

How can I get a count of all of the healthy foods attached only to the tags that are attached to 'apple' (where a healthy food is denoted by healthy_flag = 1)? Basically, for every 'apple' tag, how many healthy foods share that tag?

Was it helpful?

Solution

Found the answer here.

apple.tags.all().annotate(food_count=Count('food')).filter(food__health_flag = True)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top