[Answer]-How to serialize model class data as json

1👍

You are doing it wrong. Python comes with a json module

import json

dat = Sveti.objects.values("name", "position")
json_data = json.dumps(dat)

Sveti.objects.values creates a list of dictionaries of data containing selected fields and then you can serialize it to json with dumps
Or If you want to serialize all values you can use django serializers

from django.core import serializers
json_data = serializers.serialize("json", Sveti.objects.all())

You can use those methods to serialize Querysets that you want.

If you want to combine those data within the same json data you can use

json_data["sevni"] = serializers.serialize("json", Sveti.objects.all())
json_data["barati"] = serializers.serialize("json", Barati.objects.all())

>> print json_data

>> {"sveni": [{"id"............}, {.......}],
    "barati": [{"id"............}, {.......}] }
👤Mp0int

0👍

Acoording to this django documantation ==> https://docs.djangoproject.com/en/1.6/topics/serialization/

#select all or use some filter, no matter
barati_json = serializers.serialize("json", Barati.objects.all()) 

and return the return_json. That’s all..

//edited: concating the json contents by using a dict:

import json
return_dict = {
    'barati': barati_json,
    'some_other_integer_param1': 1,
    'some_other_param':"blabla"
}
json.dumps(return_dict)

0👍

You are constructing the JSON string by hand, which is unusual and unnecessary. I would recommend this code to return all instances of both models in JSON:

import json

def get_settings(request):
    if not request.is_ajax():
       raise Http404
    sveti_all = list(Sveti.objects.all())
    barati_all = list(Barati.objects.all())
    return HttpResponse(serializers.serialize('json', sveti_all + barati_all))
👤arocks

0👍

I’ve recently had to serialize some data to json myself and here’s what I found useful.

In models.py:

class Person(models.Model):
      id = models.IntegerField(primary_key=True)
      name = models.CharField()
      address = models.CharField()
      extra1 = models.CharField()
      extra2 = models.CharField()

def as_my_person(self):
     return {
        "id":self.id,
        "name":self.name,
        "address":self.address

     }

In the example above, I have a model that has 5 field and I only want my json data to have id, name and address.

In my views.py:

def person_view(request):
    data = Person.objects.filter(name__contains='john')
    dictionaries = [obj.as_my_person() for obj in data]
    serialized_data = simplejson.dumps(dictionaries)
    return HttpResponse(serialized_data, mimetype='application/json')

The code above should return a json string of all person with the name like ‘john’.

[{ "id":1,"name":"john smith","address":"123 Main" }, { "id": 5, "name":"john doe", "address":"123 state" }]

I’ve found that’s a quick and simple way to format and return JSON data to any front end UI framework like Kendo.

Hope it helps.

Leave a comment