2
我有一個模型有一個ForeignKey
字段。如何在序列化之後更新查詢中的json數據?
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
,我不能調用name
和client
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還是用於數據導出? – solarissmoke