Reputation: 105
how do i get gallery response like bellow. Now, galleryserializer returns response with images array with ids only. I am not able to get details of images.
json response:
{
"name": "New Gallery",
"images": [
{
id: 1,
image: 'url/path/to/image',
alt_text: 'alt'
},
{
id: 2,
image: 'url/path/to/image1',
alt_text: 'alt'
},
]
}
My models.py file:
class GalleryImage(models.Model):
image = models.ImageField(upload_to='gallery/')
alt_text = models.CharField(max_length=300)
created = models.DateTimeField(auto_now_add=True)
class Gallery(models.Model):
name = models.CharField(max_length=30)
slug = AutoSlugField(populate_from='name', unique_with='id')
images = models.ManyToManyField(GalleryImage, related_name="galleryimages")
created = models.DateTimeField(auto_now_add=True)
My serializers.py file:
class GalleryImageSerializer(serializers.ModelSerializer):
class Meta:
model = GalleryImage
exclude = '__all__'
class GallerySerializer(serializers.ModelSerializer):
class Meta:
model = Gallery
fields = '__all__'
Upvotes: 2
Views: 639
Reputation: 88539
Use nested serialization
class GallerySerializer(serializers.ModelSerializer):
images = GalleryImageSerializer(many=True)
class Meta:
model = Gallery
fields = '__all__'
Upvotes: 1