Skip to content
Advertisement

How to serialize first photo in album? Django

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.

Advertisement

Answer

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

Gallery.objects.get(photos__id=id)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement