1👍
✅
You can make your own FileField
and then work with that instead, so:
from rest_framework.fields import FileField
from rest_framework.settings import api_settings
class FileWithoutHostField(FileField):
def to_representation(self, value):
if not value:
return None
use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)
if use_url:
try:
return value.url
except AttributeError:
return None
return value.name
You can now inject the FileWithoutHostField
in the serializer_field_mapping
[drf-doc] to use this instead of the FileField
, so:
from django.db.models import fields
from django_rest.serializers import ModelSerializer
ModelSerializer.serializer_field_mapping[fields.FileField] = FileWithoutHostField
Source:stackexchange.com