我有以下三种模式(简体):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)
但我需要在模板上的画廊,而不是过度的照片进行迭代。
感谢您的建议,但是这会导致同样的错误'无法将关键字'photo_set'解析为字段...'。 – illagrenan
'Gallery.objects.filter(user_profile__id = x)。 (count_photos = Count('photo__id'))。filter(count_photos__gt = 0)' –
非常感谢,它可以和'__id'以及'__pk'一起使用。 – illagrenan