nikgaru
nikgaru

Reputation: 15

How to serialize model class data as json

I want to add a view to my django application so that it showed data from table Barati.

view.py

from django.http.response import Http404, HttpResponse
from django.template.response import TemplateResponse

from trello.models import Sveti, Barati


def get_index(request):
   return TemplateResponse(request,'index.html')

def get_settings(request):
    if not request.is_ajax():
       raise Http404
    svetebi = Sveti.objects.all()
    res = '['
    for sveti in svetebi:
        res = res + '{"name": ' + sveti.name + ', "position": ' + str(sveti.position) + ', "cards": null},'
    res = res[:-1]
    res = res + ']'
    return HttpResponse(res)

    def add_sveti(request):
    if not request.is_ajax():
        raise Http404
    sveti = Sveti()
    sveti.name = request.GET['name']
    sveti.position = request.GET['position']
    sveti.save()
    return HttpResponse('{"success":true}')

def add_barati(request):
    if not request.is_ajax():
       raise Http404
    barati = Barati()
    barati.text = request.GET['text']
    barati.position = request.GET['position']
    barati.sveti_id = request.GET['sveti_id']
    barati.save()
    return HttpResponse('{"success":true}')

models.py

 from django.db import models


 class Sveti(models.Model):
     name = models.CharField(max_length = 50, default = 'sveti')
     position = models.IntegerField()

 class Barati(models.Model):
     sveti = models.ForeignKey(Sveti)
     text = models.CharField(max_length = 10000)
     position = models.IntegerField()

I want to add information about Barati class (from the models.py) to res in json format. But I can not go further from this point

Upvotes: 0

Views: 367

Answers (4)

Eric Lee
Eric Lee

Reputation: 732

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.

Upvotes: 0

Mp0int
Mp0int

Reputation: 18737

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"............}, {.......}] }

Upvotes: 1

obayhan
obayhan

Reputation: 1732

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)

Upvotes: 0

arocks
arocks

Reputation: 2882

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))

Upvotes: 0

Related Questions