Home > Software design >  How to serialize file field without host
How to serialize file field without host

Time:07-18

I have a file field

class Document(models.Model):
    generated_document = models.FileField( # документ, который создала Celery из шаблона
        upload_to='generated_files/',
        blank=True,
        null=True
    )
    ...

I am serializing this field like this

class DocumentSerialize(serializers.ModelSerializer): class Meta: model = Document fields = ["generated_document", ...]

I want to have this /media/generated_files/expense_contract_2022-07-17-20-02-51.pdf

But I have result with host http://<HOST>/media/generated_files/expense_contract_2022-07-17-20-02-51.pdf

I know about SerializerMethodField but what is the proper way to remove host in serializer?

In urls.py i am using

if settings.DEBUG:
    urlpatterns  = static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
    )

CodePudding user response:

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
  • Related