django annotate not working properly -
i have 2 models saleitem , product. here want count of products in saleitem table . used annotate not getting 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 tried in shell. getting products 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 want totalcount of each product in saleitem table. how can that. please me.
check this: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#cheat-sheet
in example has this:
each publisher, each count of books "num_books" attribute. >>> 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 case, think should this:
sale_items = saleitem.objects.annotate(product_count=count("product__name")) then can
sale_items[0].product_count this return product count assoicated 1 sale item
Comments
Post a Comment