Why doesn't Django serialize FileField to the file url when using AWS S3

雨燕双飞 提交于 2020-01-14 03:52:30

问题


Scenario: I'm using Amazon S3 as default storage using S3 Boto and all files would be going to 'media' folder in my bucket.

Question: When I am serializing the model containing my FileField to json using serializers.serialize, all I get in the json is 'media/abc.png' or something of that sort. Is there a way to automatically get the file url in json instead of the relative path or should I manually append the url into the json response every time?


回答1:


Django operates with File objects, Storages and FileField. Filefield saves some kind of storage identifier for the file. This identifier helps storage to find the right location of the file. By default serializer gets only that identifier. And that identifier is string representation of django file object.

If you want to return url, you need to override serializer method:

from django.core import serializers
from django.db import models

JSONSerializer = serializers.get_serializer("json")

class JSONWithURLSerializer(JSONSerializer):

    def handle_field(self, obj, field):
        value = field.value_from_object(obj)
        if isinstance(field, models.FileField) and hasattr('url', value):
            self._current[field.name] = value.url
        else:
            return super(JSONWithURLSerializer, self).handle_field(obj, field)

serializer = JSONWithURLSerializer()
serializer.serialize(queryset)
data = serializer.getvalue()


来源:https://stackoverflow.com/questions/36789597/why-doesnt-django-serialize-filefield-to-the-file-url-when-using-aws-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!