Monday, December 28, 2015

Django how select one photo per gallery in one call to DB?

I have two models: 
Gallery and Photo, Photo has Gallery as FK.

Is it possible to return in one call one photo per gallery?

I already tried:
photos = Photo.objects.filter(active=True)
photos.annotate(g=Count('gallery'))
unfortunately when I call query I got something like that:

GROUP BY "wall_photo"."id", "wall_photo"."added_date", "wall_photo"."title", "wall_photo"."active", "wall_photo"."gallery_id", "wall_photo"."description"

which return me the same as above photos query without annotate :(

I tried also transform photos to SQL query and add group_by

query_photo = photos.query
query_photo.group_by = ['gallery']

Photo.objects.raw(query_photo.__str__())
and again I got the same result.

Do you know a way to do it in one call?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/07166b8b-c56b-4ef2-a2ce-c0f1266fd95a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment