我正在调用以下序列化程序 -
class ResourceSerializer(serializers.ModelSerializer):
class Meta:
model = Resmst
resource_name = 'resmst'
fields = ('resmst_id', 'resmst_name', 'resmst_desc', 'resmst_limit', 'resmst_inuse', 'resmst_active', 'resmst_lstchgtm',
'resmst_prntid', 'resmst_owner', 'resmst_public', 'resmst_locked', 'resmst_offline')
read_only_fields = ('resmst_id',)
resmst_owner是与另一个表的FK关系。我想要做的是让序列化程序显示FK所关联的列中的信息。
这是当前的json -
[
{
"resmst_id": 204,
"resmst_name": "GAWK",
"resmst_desc": null,
"resmst_limit": 1,
"resmst_inuse": 0,
"resmst_active": "Y",
"resmst_lstchgtm": "2014-08-20T11:15:18",
"resmst_prntid": null,
"resmst_owner": 822,
"resmst_public": "Y",
"resmst_locked": null,
"resmst_offline": 0
}
]
这就是我想要的样子 -
[
{
"resmst_id": 204,
"resmst_name": "GAWK",
"resmst_desc": null,
"resmst_limit": 1,
"resmst_inuse": 0,
"resmst_active": "Y",
"resmst_lstchgtm": "2014-08-20T11:15:18",
"resmst_prntid": null,
"owner_name": "John Smith",
"resmst_public": "Y",
"resmst_locked": null,
"resmst_offline": 0
}
]
或者我不得不这样做 -
[
{
"resmst_id": 204,
"resmst_name": "GAWK",
"resmst_desc": null,
"resmst_limit": 1,
"resmst_inuse": 0,
"resmst_active": "Y",
"resmst_lstchgtm": "2014-08-20T11:15:18",
"resmst_prntid": null,
"resmst_owner": {
"owner_name": "John Smith"
},
"resmst_public": "Y",
"resmst_locked": null,
"resmst_offline": 0
}
]
答案 0 :(得分:1)
Haven未对此进行测试,但看起来像this question。尝试使用SerializerMethodField
。
答案 1 :(得分:1)
我认为你应该对常规Field做得很好(注意这只是一个)。
class ResourceSerializer(serializers.ModelSerializer):
owner_name = serializers.Field(source='resmst_owner.owner_name')
class Meta:
model = Resmst
resource_name = 'resmst'
fields = ('resmst_id', 'resmst_name', 'resmst_desc', 'resmst_limit',
'resmst_inuse', 'resmst_active', 'resmst_lstchgtm',
'resmst_prntid', 'resmst_owner', 'resmst_public',
'resmst_locked', 'resmst_offline', 'owner_name', )
read_only_fields = ('resmst_id',)
别忘了将它添加到Meta.fields(如上所述)。
请参阅Core arguments:
部分来源
将用于填充的属性的名称 领域。可能是一种只接受自我论证的方法,例如 字段(来源=' get_absolute_url'),或者可以使用点分表示法 遍历属性,例如Field(source =' user.email')。
价值来源=' *'具有特殊含义,用于表示 应该将整个对象传递给该字段。这个可以 对于创建嵌套表示非常有用。 (见实施 例如,PaginationSerializer类的例子。)
默认为字段名称。