所以我在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/
1条答案
按热度按时间jucafojl1#
您可以通过覆盖
get_url(self, obj, view_name, request, format)
方法来自定义超链接字段的这种行为。此方法用于 * 将对象示例Map到其URL表示 *。举例来说:serializers.py
: