Reputation: 1397
In DRF, now if i save the image the serializer
is giving me the image with absolute path. But in my scenario, i don't want absolute path. I just need a image path which is there in DB. In my scenario, i'm hard-coding the image path in json. So i can't use the absolute path. Can anyone suggest some ideas to implement it.
Upvotes: 0
Views: 1408
Reputation: 1397
Above answers are working for list and retrieve method, but i need to add for post and retrieve instead of querying and serializing it again. Below method will work.
Normally for ImageField and FileField will return name but in DRF it's been converted to url for usefulness. So u just need to change there that's it.
In your serailizer, just specify below like that:
Field_name = serializers.ImageField(use_url=False)
So this line will convert absolute url to name as response after Save and Update.
For further reference refer this link
Upvotes: 0
Reputation: 88509
Create custom FileField
will solve the issue
class CustomFileField(serializers.FileField):
def to_representation(self, value):
if not value:
return None
if not getattr(value, 'path', None):
# If the file has not been saved it may not have a path.
return None
return value.path
class MyFooSerializer(serializers.ModelSerializer):
my_file_field = CustomFileField()
...
# other code
Upvotes: 1
Reputation: 1434
You can use SerializerMethodField
. You can return the value as it is stored in the database by doing the following:
class YourSerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
def get_image(self, obj):
return obj.image.file.name
docs: https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
Upvotes: 1