Two annotations in a single query

微笑、不失礼 提交于 2019-12-02 11:03:49

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.

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