Prefetch_related filter empty in django

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 choose pizza with their Toppings, but only those pizzas that have a certain number of toppings, for example 0,1,2?

+4
source share
1 answer

You can filter the number of fillings by annotating the request, then filtering it.

from django.db.models import Count

pizzas = Pizza.objects.annotate(
    num_toppings=Count('toppings'),
).filter(num_toppings__lt=3)

Then you can use the prefetch_relatedsame as for other queries.

pizzas = Pizza.objects.annotate(
    num_toppings=Count('toppings'),
).filter(num_toppings__lt=3).prefetch_related('toppings')
+5
source

Source: https://habr.com/ru/post/1617149/


All Articles