简体   繁体   English

Django:将QuerySet与相关对象转换为JSON

[英]Django: convert QuerySet with related objects to JSON

Let's suppose I have two simple Models: 假设我有两个简单的模型:

class Place(models.Model):
    name = models.CharField(max_length=200)
    address = models.CharField(max_length=200)

class Event(models.Model):
    name = models.CharField(max_length=200)
    date = models.DateField()
    place = models.ForeignKey(Place)

What I want to do now is query a set of events with the resolved place, and convert everything to a list of dicts, that can be converted to JSON later on. 我现在要做的是使用已解析的位置查询一组事件,并将所有内容转换为可以在以后转换为JSON的dicts列表。

This is how the end result should look like: 这是最终结果的样子:

[{
   "name": "event1",
   "date": "date1",
   "place": {
       "name": "place1",
       "address": "address1",
   },
},{
   "name": "event2",
   "date": "date2",
   "place": {
       "name": "place2",
       "address": "address2",
   },
},]

So far I tried my luck with ValueQuerySet and the .values() method: 到目前为止,我尝试使用ValueQuerySet.values()方法:

Event.objects.all().select_related("place").values()

This however won't work, since .values() only returns the ids of related objects and not the content. 但是这不起作用,因为.values()只返回相关对象的id而不返回内容。 So I was wondering if there is another built-in way to do this kind of conversion or if I have to iterate the QuerySet object and do the conversion by myself. 所以我想知道是否有另一种内置方式来进行这种转换,或者我是否必须迭代QuerySet对象并自己进行转换。

There is no default way to create the nested dicts you're after, but you can select the values of related items: 没有默认的方法来创建您之后的嵌套dicts,但您可以选择相关项的值:

# No need for select_related in this case
Event.objects.values('name', 'date', 'place__name', 'place__address')

[{
   "name": "event1",
   "date": "date1",
   "place__name": "place1",
   "place__address": "address1",
},{
   "name": "event2",
   "date": "date2",
   "place__name": "place2",
   "place__address": "address2",
}]

If absolutely necessary, you can do some post-processing in Python to get the nested dicts you want. 如果绝对必要,您可以在Python中进行一些后处理以获得所需的嵌套字符串。

There is a relevant method called model_to_dict : 有一个名为model_to_dict的相关方法:

from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])

but it won't create dict fields from related models. 但它不会从相关模型创建dict字段。

Here's the snippets you can use: 这是你可以使用的片段:

Hope that helps. 希望有所帮助。

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

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