0

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?

Adrian Martinez
  • 479
  • 1
  • 9
  • 17

2 Answers2

0

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/

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
  • This doesn't solve the problem. `Count("item")` will count all the items associated to each category included those that didn't pass the filter. – Adrian Martinez Apr 22 '17 at 07:46
0

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()
XaviP
  • 188
  • 1
  • 2
  • 8
  • Each category have multiple items but an item have only one category. I could get the number of items with a category one by one but it will make as many queries as categories you have. – Adrian Martinez Apr 22 '17 at 21:40