Home > Net >  how to just access the count of products through another model which are connected by foreign key
how to just access the count of products through another model which are connected by foreign key

Time:02-10

class Category(models.Model):
    category_name = models.CharField(max_length=50, unique=True)
    




class Product(models.Model):
    category        = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name    = models.CharField(max_length=200, unique=True)
    slug            = models.SlugField(max_length=200, unique=True)

Here what i want is just the number of the product present in each category just the number of product i know i have can fire somequery

cat = Category.objects.all()

run loop for cat

prod_cat = Product.object.filter(category=cat)

But i belive its not the efficient way to achive this

CodePudding user response:

By using annotate like this:

from django.db.models import Count

>>> categories = Category.objects.annotate(Count('product'))

>>> categories[0].product__count

CodePudding user response:

Full examples and understanding here: https://able.bio/dfernsby/django-queryset-annotations-with-conditions--19d4cb4b

  • Related