Django结果返回绝对URL

ie3xauqp  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(87)

所以我在serializers.py中有一个相当简单的序列化器

class ScheduleSerializer(serializers.ModelSerializer):

    class Meta:
        model = FrozenSchedule
        fields = ['startDate', 'endDate', 'client', 'url']

    startDate = serializers.DateField(source='start_date')
    endDate = serializers.DateField(source='end_date')
    client = serializers.StringRelatedField(many=False)
    url = serializers.URLField(source='get_absolute_url')

get_absolute_url在我的models.py

def get_absolute_url(self):
    return reverse('reports:frozenschedule-detail', kwargs={
        'slug': self.client.slug, 'pk': self.id
    })

它与viewsets.py中的ViewSet相关

class ScheduleViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = FrozenSchedule.objects.not_abandoned().future()\
        .filter(signed=False).order_by('start_date')
    serializer_class = serializers.ScheduleSerializer

它返回JSON,看起来像这样:

[
    {
        "startDate": "2016-10-01",
        "endDate": null,
        "client": "Abscissa.Com Limited",
        "url": "/clients/abscissac/frozenschedule/1",
    }
]

但我希望它返回完整的URL,而不仅仅是相对路径

[
    {
        "startDate": "2016-10-01",
        "endDate": null,
        "client": "Abscissa.Com Limited",
        "url": "http://localhost:8000/clients/abscissac/frozenschedule/1",
    }
]

我可以在我的序列化器中序列化URL吗?
Restful文档指出,rest_framework reverse函数正是我所需要的。但它需要请求对象来构建UR http://www.django-rest-framework.org/api-guide/reverse/

jucafojl

jucafojl1#

您可以通过覆盖get_url(self, obj, view_name, request, format)方法来自定义超链接字段的这种行为。此方法用于 * 将对象示例Map到其URL表示 *。举例来说:

class UrlHyperlinkedIdentityField(HyperlinkedIdentityField):
   def get_url(self, obj, view_name, request, format):
     if obj.pk is None:
       return None

    return self.reverse(view_name,
        kwargs={
            'slug': obj.client.slug,
            'pk': obj.id,
        },
        request=request,
        format=format,
    )

serializers.py

url = UrlHyperlinkedIdentityField(view_name='reports:frozenschedule-detail')

相关问题