python-Django:将具有相关对象的QuerySet转换为JSON
作者:互联网
假设我有两个简单的模型:
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)
我现在想做的是查询具有解决位置的一组事件,并将所有内容转换为字典列表,以后可以将其转换为JSON.
最终结果应如下所示:
[{
"name": "event1",
"date": "date1",
"place": {
"name": "place1",
"address": "address1",
},
},{
"name": "event2",
"date": "date2",
"place": {
"name": "place2",
"address": "address2",
},
},]
到目前为止,我尝试了ValueQuerySet和.values()方法的运气:
Event.objects.all().select_related("place").values()
但是,这将不起作用,因为.values()仅返回相关对象的ID,而不返回内容.因此,我想知道是否存在另一种内置方法来进行这种转换,或者是否必须迭代QuerySet对象并自己进行转换.
解决方法:
没有默认的方法来创建嵌套的字典,但是您可以选择相关项目的值:
# 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",
}]
如果绝对必要,则可以在Python中进行一些后处理以获得所需的嵌套字典.
标签:django-queryset,json,python,django,django-models 来源: https://codeday.me/bug/20191030/1968804.html