2017-02-27 84 views
1

DRF默認序列化一個filefield或imagefield路徑到它的相對路徑。Django REST Framework和FileField絕對URL位於同一字段

如在此質疑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" 
} 

回答

2

您可以覆蓋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 
+0

謝謝,就像一個冠軍 – lapinkoira

+0

@lapinkoira歡迎您 –

相關問題