在我的Django项目中,我的View正在将ValuesQuerySet
转换为JSON字符串:
import json
# ...
device_list = list(Device.objects.values())
device_json = json.dumps(device_list)
生成的JSON字符串:
[{"field1": "value", "location_id": 1, "id": 1, "field2": "value"},
{...}]
如何将数据包含在"location_id": 1
所代表的位置对象中,而不是ID号?像这样:
[{"field1": "value", "location_name": "name", "location_region": "region", "another_location_field": "value", "id": 1, "field2": "value"},
{...}]
答案 0 :(得分:1)
我发现您可以使用Field Lookups来关注其他相关模型中的关系和访问字段:
import json
# ...
device_list = list(Device.objects.values('field1', 'field2', 'location__name', 'location__region'))
json.dumps(device_list)
生成的JSON字符串:
[{field1": "value", "field2": "value", "location__name": "name", "location__region": "region"},
{...}]