class Category(models.Model):
name = models.CharField(max_length=20)
class Product(models.Model):
name = models.CharField(max_length=64)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
To get the number products for each category:
>>> categories = Category.objects.annotate(Count('product'))
This adds the <field_name>__count
attribute to each instance returned:
>>> categories.values_list('name', 'product__count')
[('Clothing', 42), ('Footwear', 12), ...]
You can provide a custom name for your attribute by using a keyword argument:
>>> categories = Category.objects.annotate(num_products=Count('product'))
You can use the annotated field in querysets:
>>> categories.order_by('num_products')
[<Category: Footwear>, <Category: Clothing>]
>>> categories.filter(num_products__gt=20)
[<Category: Clothing>]