'How to do SELECT COUNT(*) GROUP BY of ForeignKey field in Django?

Let's say we have three models:

class Category(models.Model):
    name = models.CharField(max_length=255)

class Platform(models.Model):
    name = models.CharField(max_length=255)

class Product(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE, related_name='products')

class SellingItem(models.Model):
    name = models.CharField(max_length=255)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='selling_items')
    price = models.DecimalField(max_digits=5, decimal_places=2)

The idea here is to get a total of the different categories and platforms based on a SellingItem's queryset.

My initial approach is:

categories = queryset.values('product__category__id', 'product__category__name', 'product__category__label').annotate(total=Count('product__category__id'))  # noqa: E501
platforms = queryset.exclude(product__platform__isnull=True).values('product__platform__id', 'product__platform__name', 'product__platform__label').annotate(total=Count('product__platform__id'))  # noqa: E501

The problem is that the result is not grouped...

The code is working on based on a Product's queryset if removing all product__ in the previous code.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source