Two annotations in a single query

时光毁灭记忆、已成空白 提交于 2020-01-11 13:34:19

问题


I am trying to build a query set to do a count, the query set involves three models.

class Owner(models.Model): name = models.CharField(max_length=10, null=False)

class Location(models.Model): name = models.CharField(max_length=10, null=False) owner = models.ForeignKey(Owner, on_delete=models.SET_NULL, null=True, blank=True)

class Asset(models.Model): name = models.CharField(max_length=10, null=false) owner = models.ForeignKey(Owner, on_delete=models.SET_NULL, null=True, blank=True) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True)

I am trying to do a count for Locations for the owner and Assets for the owner, I can achieve this as two separate Querysets as follows:

locations = Owner.objects.all().annotate(locations=Count('location'))

assets = Owner.objects.all().annotate(assets=Count('asset'))

This works fine, but what I'm trying to do is get a single row for both values and build a table similar to the one below.

| Owner | Assets | Locations | |--------+--------+-----------| | owner1 | 10 | 3 | | owner2 | 100 | 20 | | owner3 | 70 | 50 |

I've tried to put both annotations in a single query but I don't appear to get the right results, the count is either the same for both assets and location or I get very large numbers which I assume because both count operations are impacting each other.

Query below gives me the same numbers for both asset and location

queryset = Owner.objects.all().annotate(assets=Count('asset'), locations=Count('location'))

or

Query below gives me large numbers for both asset and location

queryset = Owner.objects.all().annotate(assets=Count('asset')).annotate(locations=Count('location'))

I can do this directly with SQL but I'm hoping not do go down that path.


回答1:


Thanks Nara, I tried a different permutation of what you suggested which ended up working.

queryset = Owner.objects.all().annotate(assets=Count('asset', distinct=True), locations=Count('location', distinct=True))

Here is what it looks like from a Django shell.

>>> from inventory.models import *
>>> from django.db.models import Count
>>> queryset = Owner.objects.all().annotate(assets=Count('asset', distinct=True), locations=Count('location', distinct=True))
>>> vars(queryset[0])
{'_state': <django.db.models.base.ModelState object at 0x0427B230>, 'id': 1, 'name': 'Owner 1', 'assets': 5, 'locations': 4}
>>> vars(queryset[1])
{'_state': <django.db.models.base.ModelState object at 0x0427B2D0>, 'id': 2, 'name': 'Owner 2', 'assets': 3, 'locations': 4}
>>> vars(queryset[2])
{'_state': <django.db.models.base.ModelState object at 0x0427B4D0>, 'id': 3, 'name': 'Owner 3', 'assets': 2, 'locations': 6}

As you can see that gives me both the asset and the location counts.



来源:https://stackoverflow.com/questions/52798494/two-annotations-in-a-single-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!