Django - Get a set of objects from many in one ratio

Please take a look at these models:

class Album(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) pub_date = models.DateTimeField(default=datetime.now) class Photo(models.Model): album = models.ForeignKey(Album, default=3) image = models.ImageField(upload_to=get_upload_file_name) caption = models.CharField(max_length=200) pub_date = models.DateTimeField(default=datetime.now) 

How to get a set of photos for a specific album ??? And how to get an album from the photo itself?

I tried this:

 # To get the set of photos from the user (tika) album: >>>t = User.objects.get(username='tika') >>>t_album = Album.objects.get(user=t) >>>t_album <Album: tika_album> >>>t_album.image_set.all() AttributeError: 'Album' Object has no attribute 'image_set' 

Please guide me in the right direction. Thanks.

+6
source share
2 answers

You are almost there. you should use photo_set instead of image_set

 >>>t_album.photo_set.all() 

_set named _set

If you need a list of photos in 1 request,

 photos = Photo.objects.filter(album__user__username='tika') 
+9
source

Better yet, you can write in Photo

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

photos is the name of the return field from Album to Photo . If you do not define it, the return field will be called photo_set .

Then you use

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

or

 t_album.photo_set.all() 
+7
source

Source: https://habr.com/ru/post/957458/


All Articles