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

标签 python django django-views

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

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/

相关文章:

python - 当我运行 Celery worker 时出现 AttributeError

python - Django 表已经存在

python - 使用 python 从文件中打印行返回列中的值,而不是按行

Django 测试装置和内容类型

javascript - 无法使用 Jquery 从 Freebase 导出额外数据

python - 根据要求生成 django tar

python - 使用 json 序列化查询集的结果引发错误 :

python - 致命 python 错误 :initfsencoding:unable to load the file system codec? 的原因可能是什么

python - 对 WSGI 中的 : Django "could not import app.views" but can import app, 感到困惑?

python - 如何在 Django 中显示自定义 404.html 页面