2015-11-23 46 views
4
class Topping(models.Model): 
    name = models.CharField(max_length=30) 

class Pizza(models.Model): 
    name = models.CharField(max_length=50) 
    toppings = models.ManyToManyField(Topping) 

是否可以选择比萨饼和他们的浇头,但只有那些比萨饼,有一定数量的浇头,如0,1,2?在django中过滤prefetch_related空

回答

5

您可以通过对查询集进行注释,然后对其进行过滤来过滤浇注的数量。

from django.db.models import Count 

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

然后可以使用prefetch_related您为其他查询集做同样的方式。

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