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

27 views
Skip to first unread message

piasek piasek

unread,
Dec 28, 2015, 4:29:21 PM12/28/15
to Django users
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?
Reply all
Reply to author
Forward
0 new messages