Question

I have following three models (simplified):

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

On profile detail I want to show all galleries that have at least one photo.

I tried to go this way:

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

But this leads to an error:

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

I understand, that Gallery.objects.all() is Queryset, so this is probably not possible. Solution could be to start from Photo:

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

But I need to iterate in template over galleries and not over photos.

Was it helpful?

Solution

You should use

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

In annotate, it is not X_set but just X.

OTHER TIPS

This would also work,, Shorthand for above:

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

One more way to Make this query:

 Gallery.objects.filter(user_profile__id=x, photo__isnull=False).distinct()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top