[Fixed]-Django rest framework changing id to url

1πŸ‘

βœ…

Yes, DRF is extremely flexible and can support this. I would suggest using a SerializerMethodField for this capability. It essentially allows you to map a serializer field to the result of a custom function.

Your implementation would look like this:

class CollectionSerializer(ModelSerializer):
    images = serializers.SerializerMethodField()

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]

    def get_images(self, obj):
        return [collection_image.image.url for collection_image in obj.images]

Source:
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

** the field is mapped to the method via the β€œget_” naming convention

πŸ‘€Rob

0πŸ‘

Can set depth=1 to unfold all related models one level deep:

class CollectionSerializer(ModelSerializer):

    class Meta:
        model = Collection
        fields = [
            'id',
            'name',
            'description',
            'publish',
            'author',
            'images',
        ]
        depth = 1
πŸ‘€serg

Leave a comment