user12510360
user12510360

Reputation:

Data manipulation in Django json response

I want to iterate over device object and add a comparison.

The json looks like below. I want to compare let's say if status is 1 to add new field for each device "status" : "available" else "status" : "Occuppied". How can i manipulate json like that?

View:

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
      }
   }
]

Upvotes: 0

Views: 655

Answers (1)

jaap3
jaap3

Reputation: 2846

Django's built in serializers are very basic, if you are building some sort of JSON API I'd strongly recommend to check out Django REST Framework (https://www.django-rest-framework.org/). Which allows you to build custom serializers.

To answer you question, it's probably easiest to use the 'python' serializer, manipulate the data and then return a JsonResponse, something like this:

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

Upvotes: 2

Related Questions