Django ORM - 按多个级别的相关计数进行过滤

时间:2014-04-25 06:36:41

标签: django django-models django-orm

我有以下三个模型(简化):

from django.db import models

class UserProfile(models.Model):
    pass

class Gallery(models.Model):
    user_profile = models.ForeignKey('UserProfile')

class Photo(models.Model):
    gallery = models.ForeignKey('Gallery')

在个人资料详细信息中,我想要显示至少包含一张照片的所有图库

我试着这样:

Gallery.objects.all().filter(user_profile__pk=x). \
    annotate(count_photos=Count('photo_set')).filter(count_photos__gt=0)

但这会导致错误:

FieldError: Cannot resolve keyword 'photo_set' into field. Choices are: id, user_profile

我理解,Gallery.objects.all()Queryset,所以这可能是不可能的。解决方案可以从Photo开始:

Photo.objects.all().filter(gallery__user_profile__pk=x)

但我需要在模板上迭代画廊,而不是照片。

2 个答案:

答案 0 :(得分:2)

你应该使用

 Gallery.objects.filter(user_profile__id=x)
                .annotate(count_photos=Count('photo__id'))
                .filter(count_photos__gt=0)

在注释中,它不是X_set而只是X

答案 1 :(得分:0)

这也可以,上面的简写:

 Gallery.objects.filter(user_profile__id=x)
                .annotate(count_photos=Count('photo'))
                .filter(count_photos__gt=0)

另一种方式来进行此查询:

 Gallery.objects.filter(user_profile__id=x, photo__isnull=False).distinct()