django 序列化外键对象 [英] django serialize foreign key objects

查看:23
本文介绍了django 序列化外键对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有几个问题在问同样的事情.但它们是 2010 年的,对我帮助不大.所以我认为自 2010 年以来这方面可能有所更新?

There are couple of question asking for the same thing already. But they are from 2010, and it didn't help me so much. So I figure it maybe been some update to this front since 2010?

在 google 上我发现了这个 link,它解释了用法自然键.然而,我的问题是从 django.contrib.auth.models.User 获取异物,所以它没有帮助.

On google I found this link, which explain usage of natural keys. However my problem concerns of getting foreign objects from django.contrib.auth.models.User so it doesn't help.

我的问题如下.我想序列化 QuerySet 所以我也得到外键对象,因为我想将它作为 JSON 传递给客户端.django.core 中的序列化程序不会这样做.所以在我的例子中,我已经向模型添加了另一个字段以包含我需要的来自外部对象的值.但是它引入了冗余数据.

My problem is as following. I want to serialize the QuerySet so I get the foreign key objects also, because I want to pass it as JSON to the client. The serializer from django.core doesn't do that. So in my case to simply the problem I had added another field to the model to contain the value I need from the foreign object. But it however introduce redundant data.

我的示例模型包含 username,如果可能,我希望将其删除,而是通过外键获取.

My example model it contains the username which I would like if possible remove, and instead get it by the foreign key.

    user = models.ForeignKey(User)
    username = models.CharField(max_length=100, null=False)

推荐答案

解决此问题的一种可能方法是根据查询集的返回构造您自己的字典对象.你会做这样的事情:

One potential way around this is to construct your own dictionary object based on the returns of a queryset. You'd do something like this:

queryset = Model.objects.all()
list = [] #create list
for row in queryset: #populate list
    list.append({'title':row.title, 'body': row.body, 'name': row.user.username})
recipe_list_json = json.dumps(list) #dump list as JSON
return HttpResponse(recipe_list_json, 'application/javascript')

您需要导入 json 才能正常工作.

You need to import json for this to work.

import json

这篇关于django 序列化外键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆