DRF默认序列化为其相对路径的文件字段或图像域路径。
喜欢这个问题Django REST Framework and FileField absolute url
我知道可以生成一个名为“file_url”的自定义字段并序列化完整路径。
但是可以在同一个字段中序列化吗?像:
class Project(models.Model):
name = models.CharField(max_length=200)
thumbnail = models.FileField(upload_to='media', null=True)
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ( 'id' ,'url', 'name', 'thumbnail')
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
{
"id": 1,
"url": "http://localhost:8000/api/v1/projects/1/",
"name": "Institutional",
"thumbnail": "ABSOLUTE URL"
}
答案 0 :(得分:4)
你可以覆盖to_representation
方法并在那里写一个绝对路径:
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ( 'id' ,'url', 'name', 'thumbnail')
def to_representation(self, instance):
representation = super(ProjectSerializer, self).to_representation(instance)
domain_name = # your domain name here
full_path = domain_name + instance.thumbnail.url
representation['thumbnail'] = full_path
return representation