I have being playing with this for hours with out find a solution.
I have the following models:
class Category(models.Model):
name = models.CharField(max_length=100)
class Item(models.Model):
name = models.CharField(max_length=250)
category = models.ForeignKey(Category)
Then I filter the Items and the categories related to that item:
items = Item.objects.filter(name=name)
categories = Category.filter(id__in = items.values_list('category__id'))
Now I want to get the number of the items with a category and save that number in a field in categories with annotate
How can I do it?
Try the following code
from django.db.models import Count
items = Item.objects.filter(name=name)
categories = Category.objects.filter(
id__in=items.values_list('category_id')
).annotate(items_count=Count("item"))
for cat in categories:
print cat.name, cat.items_count
for reference: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/
Then I filter the Items and the categories related to that item.
If each item can point to several categories, I think you need ManyToMany field.
Now I want to get the number of the items with a category
category = Category.objects.filter(name=name)
num_items = Item.objects.filter(category=category).count()