简体   繁体   English

django序列化外键对象

[英]django serialize foreign key objects

There are couple of question asking for the same thing already. 有几个问题要求同样的事情。 But they are from 2010, and it didn't help me so much. 但它们是从2010年开始的,它对我帮助不大。 So I figure it maybe been some update to this front since 2010? 所以我认为自2010年以来这可能是对这方面的一些更新?

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. 但是我的问题是从django.contrib.auth.models.User获取外来对象,所以它没有帮助。

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. 我想序列化QuerySet,所以我也得到了外键对象,因为我想把它作为JSON传递给客户端。 The serializer from django.core doesn't do that. 来自django.core的序列化程序不会这样做。 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. 但它引入了冗余数据。

My example model it contains the username which I would like if possible remove, and instead get it by the foreign key. 我的示例模型包含我想要的username ,如果可能的话删除,而是通过外键获取它。

    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')

You need to import json for this to work. 你需要导入json才能工作。

import json

您可以使用Django REST框架的序列化程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM