我在 django-rest 框架中有一个 api,现在返回这个 json 数据:
[
{
"id": 1,
"foreignobject": {
"id": 3
},
"otherfields": "somevalue"
}
]
但我希望它返回类似这样的内容(仅将 foreigneky 展平为其 ID):
[
{
"id": 1,
"foreignobject_id":3,
"otherfields": "somevalue"
}
]
在模型资源中执行此操作,现在我有(简化):
class ForeignKeyInDataResource(ModelResource):
model = TheOtherModel
fields = ('id',)
class SomeModelResource(ModelResource):
model = SomeModel
fields = ( 'id',('foreignobject','ForeignKeyInDataResource'),'otherfields',)
我已经尝试过类似的东西:
class SomeModelResource(ModelResource):
model = SomeModel
fields = ( 'id','foreignobject__id','otherfields',)
但这没有用
对于完整的故事,这是视图返回数据的方式,列表是对 SomeModel 查询的结果:
data = Serializer(depth=2 ).serialize(list)
return Response(status.HTTP_200_OK, data)