[Django]-Save related Images Django REST Framework

3👍

So my solution is based off of this post and works quite well but seems very unrobust and hacky.

I change the images field from a relation serializer requiring a dictonary to a ListField. Doing this i need to override the list field method to actually create a List out of the RelatedModelManager when calling “to_repesentation”.

This baiscally behaves like a list on input, but like a modelfield on read.

class ModelListField(serializers.ListField):
    def to_representation(self, data):
        """
        List of object instances -> List of dicts of primitive datatypes.
        """
        return [self.child.to_representation(item) if item is not None else None for item in data.all()]


class ListingSerializer(serializers.ModelSerializer):
    images = ModelListField(child=serializers.FileField(max_length=100000, allow_empty_file=False, use_url=False))

    class Meta:
        model = Listing
        fields = ('name', 'images')

    def create(self, validated_data):
        images_data = validated_data.pop('images')
        listing = Listing.objects.create(**validated_data)
        for image_data in images_data:
            ListingImage.objects.create(listing=listing, image=image_data)

        return listing

Leave a comment