gpt4 book ai didi

python - Django 结果返回绝对 URL

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:01 24 4
gpt4 key购买 nike

所以我在 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/

最佳答案

覆盖 HyperlinkedIdentityField .它有以下方法,

get_url(self, obj, view_name, request, format)

可以是used to map the object instance to its URL representation .即,

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')

关于python - Django 结果返回绝对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39634342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com