Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter prefetch_related 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 Select Pizzas with their Toppings, but only those pizzas, that have certain number of toppings, like 0,1,2?

like image 320
Andrew Fount Avatar asked Nov 23 '15 23:11

Andrew Fount


1 Answers

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')
like image 155
Alasdair Avatar answered Oct 02 '22 08:10

Alasdair