[Django]-Django – Get the set of objects from Many To One relationship

33👍

You are almost there. you should be using photo_set instead of image_set

>>>t_album.photo_set.all() 

i.e the lowercase modelname with _set

If you want the list of photos in 1 query,

photos = Photo.objects.filter(album__user__username='tika')

26👍

Even better, you can write, in Photo

album = models.ForeignKey(Album, related_name='photos', default=3)

The photos will be the name of the reverse field from Album to Photo. If you don’t define it, the reverse field will be named photo_set.

You then use

t_album.photos.all()  # only if you've defined the `related_name` argument to 'photos'

or

t_album.photo_set.all()

Leave a comment