简体   繁体   中英

Count within a count, in Django ORM

Hi I am the following structure

class Vegetable(models.Model):
    vegetable_name = models.Chafield(max_legnth = 100)

class Buyer(models.Model):
    buyer_name = models.Chafield(max_legnth = 100)

Class Holding(models.Model):
    vegetable = models.ForeignKey(Vegetable)
    buyer = models.ForeignKey(Buyer)

I want to get the count of which buyer holds a particular vegetable and also the total number of units of that particular vegetable held.Of course I can use filters and annotations, but they give me a dictionary.For example I can use

Holding.objects.filter(vegetable__pk='223').values('buyer').annotate(tcount=Count('buyer'))

(Just an example )

This gives me the following list as answer:

[{'buyer': '111', 'tcount': 3}, {'buyer': u'112', 'tcount': 4}, {'buyer': u'113', 'tcount': 3}]

now the total holding or the vegetable is 3 + 4 + 3 = 10

I will have to go through additional computation of iterating through the dictionaries and retrieving the values for count and adding them.Also I dont want to make an additional query, just to get the holding of the vegetable with pk = '223'. Can I somehow get all this information only with one ORM query and also not perform any iterative computation.

要获取所有买家中特定蔬菜的总数,您可以:

Vegetable.objects.filter(vegetable_name="Carrot").count()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM