Home > Software engineering >  How to serialize first photo in album? Django
How to serialize first photo in album? Django

Time:11-06

How to serialize first photo in album if photo connected by using FK with model Gallery. I need first photo for gallery cover in galley list. My models:

class Gallery(models.Model):
    title = models.CharField()

class GalleryImage(models.Model):
    gallery_id = models.ForeignKey(Gallery, related_name='photos')
    photo = models.ImageField()

Anyone have any ideas? May be I need suchlike request Gallery.objects.get(id=id).photos.first() but i not sure is it correct.

CodePudding user response:

get returns only one object. filter returns multiple objects. You can access the ForeignKey fields with __.

Gallery.objects.get(photos__id=id)
  • Related