序列化后如何从查询中更新json数据?

时间:2016-05-07 05:11:18

标签: python json django django-models django-views

我的模型有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
}
]"

它看起来并不酷,因为它只返回id的{​​{1}},我无法调用client的{​​{1}}和name。那么如何更新json以便看起来像这样:

address

或者还有另一种方法可以在模板中调用client "[ { "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 } ]" name吗?

非常感谢您的回答......

1 个答案:

答案 0 :(得分:1)

Django有Natural Keys。看看这个。