Gregory
Gregory

Reputation: 3

In django serializer response, how to get rid of absolute path (media_url prefix) for FileField?

I have used a models.FileField() in my model and I have created a simple ModelSerializer and CreateAPIView for it. As I am using AWS S3, when posting a file, I receive Json response that includes MEDIA_URL as prefix of filename i.e.:

{
    "id": 32,
    "file": "https://bucket.digitaloceanspaces.com/products/capture_a50407758a6e.png"
}

What i would like to achieve instead is to either keep only a file name:

{
    "id": 32,
    "file": "capture_a50407758a6e.png"
}

or to be able to change the prefix to some other:

{
    "id": 32,
    "file": "https://google.com/capture_a50407758a6e.png"
}

The change should only be visible in Json response and and the database entry. The S3 details should be still sourced as they are from settings.py.

Hope it makes sense.

Let me know if anyone has any idea as I'm only able to find solution for providing full/absolute path.

Thanks

Upvotes: 0

Views: 253

Answers (1)

Connor Fogarty
Connor Fogarty

Reputation: 326

I think what you're looking for is the serializer method to_representation.

In your case, this might look like:

import os

class MySerializer(serializers.ModelSerializer):
    # serializer contents

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['file'] = os.path.basename(ret['file'])

        return ret

That should make the serializer return all normal values besides the basename of the file!

Upvotes: 1

Related Questions