tstudent
tstudent

Reputation: 89

django annotate not working properly

I have two models SaleItem and Product. Here i want to get the count of the products in the SaleItem table . I used annotate but not getting the desired result

class SaleItem(models.Model):
    product = models.ForeignKey(Product, related_name="sale_products")
    quantity = models.PositiveIntegerField()


class Product(models.Model):
    name = models.CharField(max_length=128)

views.py

SaleItem.objects.values("product__name").annotate(count=Count("product__name"))

when i tried this in shell. i am getting all the products with count 1

<QuerySet [{'count': 1, 'product__name': u'Rice'}, {'count': 1, 'product__name': u'Rice'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Mango'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Apple'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}, {'count': 1, 'product__name': u'Grape'}]>

here i want the totalcount of the each Product in the SaleItem table. How can i do that. Somebody please help me.

Upvotes: 3

Views: 3810

Answers (1)

Marshall X
Marshall X

Reputation: 794

Check this: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#cheat-sheet

in the example it has this:

Each publisher, each with a count of books as a "num_books" attribute.
>>> from django.db.models import Count
>>> pubs = Publisher.objects.annotate(num_books=Count('book'))
>>> pubs
<QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>
>>> pubs[0].num_books
73

Applying it to your case, I think it should be something like this:

sale_items = SaleItem.objects.annotate(product_count=Count("product__name"))

then you can do

sale_items[0].product_count

this will return the product count assoicated with one sale item

Upvotes: 2

Related Questions