修改serializers.HyperlinkedIdentityField生成的url路径

时间:2018-03-14 20:36:38

标签: python django django-rest-framework

是否有一种简单的方法来修改serializers.HyperlinkedIdentityField生成的超链接?具体来说,我想将/download追加到网址路径。

> class AbcSerializer(serializers.HyperlinkedModelSerializer):
>     url = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail")
>     url_download = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail") #append /download to this url
> 
> class Meta:
>     model = abc
>     fields = ('url', 'url_download')

1 个答案:

答案 0 :(得分:0)

将视图更改为包含在网址中下载的视图

Subclass HyperlinkedIdentityField并覆盖get_url以包含/下载

class HyperlinkedDownloadIdentityField(HyperlinkedIdentityField):
      def get_url(self, *args):
             url = super().get_url(*args)
             return url+"/download"

和序列化程序

...
url_download = HyperlinkedDownloadIdentityField(view_name="api:v1:abc-detail")