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

问题描述





  • Serialize django model with foreign key models
  • Serializing Foreign Key objects in Django
  • get foreign key objects in a single query - 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上我发现这个,其中说明了使用。然而,我的问题是从 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.

我的示例模型包含用户名,如果可能,我想删除,而不是通过外键获取它。

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序列化外键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:32