gpt4 book ai didi

python - Django json 响应中的数据操作

转载 作者:行者123 更新时间:2023-11-30 21:51:44 25 4
gpt4 key购买 nike

我想迭代设备对象并添加比较。

json 如下所示。我想比较一下,如果 status 为 1,则为每个设备添加新字段 "status": "available" else "status": "Occuppied"。我怎样才能像这样操作json?

查看:

from django.core import serializers

def ApplicationDetail(request, application_id, cat):
device = Device.objects.all().filter(category=cat)
data = serializers.serialize('json', device)
return HttpResponse(data, content_type='application/json')

JSON:

[ 
{
"model":"applications.device",
"pk":"70b3d5d720040338",
"fields":{
"icon_name":"amr.jpg",
"application_id":13,
"status":1
}
},
{
"model":"applications.device",
"pk":"70b3d5d72004034c",
"fields":{
"icon_name":"amr.jpg",
"application_id":13,
"status":0
}
}
]

最佳答案

Django 的内置序列化器非常基本,如果您正在构建某种 JSON API,我强烈建议您查看 Django REST Framework ( https://www.django-rest-framework.org/ )。它允许您构建自定义序列化器。

要回答您的问题,最简单的方法可能是使用 'python' 序列化器,操作数据,然后返回 JsonResponse,如下所示:

from django.http import JsonResponse

...
data = serializers.serialize('python', device)
for row in data:
row['fields']['status'] = 'available' if row['fields']['status'] else 'occupied'
return JsonResponse(data, safe=False)

In order to serialize objects other than dict you must set the safe parameter to False https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects

关于python - Django json 响应中的数据操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60059881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com