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

2024-09-30 19:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

它看起来不酷,因为它只是返回idclient,我不能调用nameaddressclient。因此,如何更新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
}
]"

或者有另一种方法在模板中调用nameaddressclient?你知道吗

非常感谢你的回答。。。你知道吗


Tags: nameclientidjsonfieldsmodeladdressmodels