2014-04-25 29 views
0

我有以下三种模式(简体):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) 

但我需要在模板上的画廊,而不是过度的照片进行迭代。

+0

感谢您的建议,但是这会导致同样的错误'无法将关键字'photo_set'解析为字段...'。 – illagrenan

+0

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

+0

非常感谢,它可以和'__id'以及'__pk'一起使用。 – illagrenan

回答

2

您应该使用

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

在注解,它不X_set只是X

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