Reputation: 81
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.
Upvotes: 1
Views: 2722
Reputation: 7376
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)
Upvotes: 4