Django REST framework serializer 嵌套显示绝对路径

时间:2024-11-02 12:05:07

Django REST framework官方文档提到,当调用Serializer时,应当传入request参数,以便生成完整的url而不是相对url。使用ModelSerializerrequest会被自动传入。当在ModelSerializer中嵌套其他Serializer时,需要手动传入request。示例如下:

class ExampleSerializer(ModelSerializer):
child = ChildSerializer(context={'request': self.context['request']) class Meta:
model = ExampleModel
fields = "__all__"