I have these models:
class IceCream(models.Model):
name = models.CharField(max_length=255)
class Topping(models.Model):
name = models.CharField(max_length=255)
ice_cream = models.ForeignKey(IceCream, on_delete=models.CASCADE, related_name="toppings")
is_active = models.BooleanField(db_index=True)
I would like to run the following query to get a list of all ice creams, together with a count of the total number of available toppings, which in SQL would look like this:
SELECT ice_cream.*,
(SELECT COUNT(id) FROM topping WHERE topping.ice_cream = ice_cream.id AND topping.is_active = True) AS total_toppings
FROM ice_cream
This is a simplified version and there are more parameters in there, but if I can make this work, then things should work out. Can I do this in Django using Subquery expressions? I have not managed to make it work. Or are raw queries my only way out here because of the COUNT that I want to include in the subquery?