Paul R
Paul R

Reputation: 2797

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?

Upvotes: 6

Views: 1502

Answers (1)

Alasdair
Alasdair

Reputation: 308839

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')

Upvotes: 7

Related Questions