【发布时间】:2016-09-02 06:09:32
【问题描述】:
我有一个具有ForeignKey 字段的模型。
class Client(models.Model):
# more fields
name = models.CharField()
address = models.TextField()
class FessapComment(models.Model):
# more fields
timestamp = models.DateTimeField(auto_now=True)
client = models.ForeignKey(Client)
关于视图,我进行filter 查询。
comments = FessapComment.objects.filter(fessap_id=fessap_id)
并进行序列化。
json_data = serializers.serialize('json', comments)
return JsonResponse(json_data, safe=False)
就像我们现在一样,这是 json 的样子:
"[
{
"fields":
{
"timestamp": "2016-05-06T13:39:46.584Z",
"client": "U2B3DBDC",
},
"model": "socmed.fessapcomment",
"pk": 1
},
{
"fields":
{
"timestamp": "2016-05-06T15:23:12.641Z",
"client": "U26A6E19",
},
"model": "socmed.fessapcomment",
"pk": 2
}
]"
它看起来并不酷,因为它只返回client 的id,我不能调用client 的name 和address。那么如何更新该 json 以使其看起来像这样:
"[
{
"fields":
{
"timestamp": "2016-05-06T13:39:46.584Z",
"client":
{
"id": "U2B3DBDC",
"name": "Herman James",
"address": "Uooepi St.",
},
},
"model": "socmed.fessapcomment",
"pk": 1
},
{
"fields":
{
"timestamp": "2016-05-06T15:23:12.641Z",
"client":
{
"id": "U26A6E19",
"name": "Jared",
"address": "Ter St.",
},
},
"model": "socmed.fessapcomment",
"pk": 2
}
]"
或者还有其他方法可以在模板中调用client 的name 和address?
非常感谢您的回答...
【问题讨论】:
-
你想对序列化的数据做什么?是用于某种 API 还是用于数据导出?
标签: python json django django-models django-views