根据Django中的对象计数过滤一对多关系

时间:2016-02-18 19:10:07

标签: python django django-queryset

我有四个与餐馆有关的模型,我很难返回正确的结果。

模型为AdminEnteredRestaurantRestaurantPhotoMenu,定义如下:

class AdminEnteredRestaurant(models.Model):
    restaurant = models.OneToOneField(Restaurant)
    ...

class Restaurant(models.Model):
    name = models.CharField(max_length= 100)
    ...

class Photo(models.Model):
    restaurant = models.ForeignKey(Restaurant)
    ...

class Menu(models.Model):
    restaurant = models.OneToOneField(Restaurant)
    ...

我想要的查询是过滤所有AdminEnteredRestaurant并仅返回具有1个或更少AdminEnteredRestaurant个和0个菜单的Photocompile ('com.ourcompany:sdk:2.1.16@aar') { transitive = true } 。我该怎么做呢?

1 个答案:

答案 0 :(得分:4)

我会使用Countannotatelteisnull来制作类似

的内容
from django.db.models import Count
results = AdminEnteredRestaurant.objects.annotate(num_photos=Count('restaurant__photo')) \
                                        .filter(num_photos__lte=1) \
                                        .filter(restaurant__menu__isnull =True)