问题
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