Search code examples
djangoapidjango-rest-frameworkdjango-serializer

Django reverse relationship in many-to-many field


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__'


Solution

  • Use nested serialization

    class GallerySerializer(serializers.ModelSerializer):
        images = GalleryImageSerializer(many=True)
        class Meta:
            model = Gallery
            fields = '__all__'