Django - QuerySet - Get count for all determined child objects inside all parent objects

感情迁移 提交于 2019-12-24 08:11:46

问题


I've got this model:

class Order(models.Model):
    #bunch of fields#

class Laptop(models.Model):
    #bunch of fields#

class Camera(models.Model):
    #bunch of fields#

class MusicPlayer(models.Model):
    #bunch of fields#

The last three have a foreign key associated to the Order class. I need to retrieve via a QuerySet the summed count for each child object for all orders, grouped by each one of them.

The result should look something like this: Laptop:5 Camera:10 MusicPlayer:1

I've tried using different django queries but all I get to is retrieving the count for each order instead the count for all orders.

I know this could be easily done by just querying each one separately but I was requested to do all in one query.


回答1:


Add related_name to your models:

class Laptop(models.Model):
    order = models.ForeignKey(Order, related_name='laptops')

class Camera(models.Model):
    order = models.ForeignKey(Order, related_name='cameras')

class MusicPlayer(models.Model):
    order = models.ForeignKey(Order, related_name='music_players')

And then you can retrieve number of related models using annotate and Count:

from django.db.models import Count

orders = Order.objects.annotate(laptops_count=Count('laptops'), cameras_count=Count('cameras'), music_players_count=Count('music_players'))
print(orders.laptops_count)
print(orders.cameras_count)
print(orders.music_players_count)


来源:https://stackoverflow.com/questions/39002617/django-queryset-get-count-for-all-determined-child-objects-inside-all-parent

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