class Topping(models.Model):
name = models.CharField(max_length=30)
class Pizza(models.Model):
name = models.CharField(max_length=50)
toppings = models.ManyToManyField(Topping)
Is it possible to Select Pizzas with their Toppings, but only those pizzas, that have certain number of toppings, like 0,1,2?
You can filter on the number of toppings by annotating the queryset, then filtering it.
from django.db.models import Count
pizzas = Pizza.objects.annotate(
num_toppings=Count('toppings'),
).filter(num_toppings__lt=3)
You can then use prefetch_related
the same way that you do for other querysets.
pizzas = Pizza.objects.annotate(
num_toppings=Count('toppings'),
).filter(num_toppings__lt=3).prefetch_related('toppings')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With