Gunjan
Gunjan

Reputation: 3

Django - JSON serializers.serialize not working

I have the following code in views.py and I want to get the entire list of persons in a sate.

def all_json_persons(request, state):
    print "current_state--" + str(state)
    current_state = State.objects.get(id=state)
    print "current_state--" + str(current_state)
    districts = District.objects.all().filter(state=state)
    print "districts--" + str(districts)
    personsList = []
    for current_district in districts:
       villages = Address.objects.all().filter(district=current_district) 
       for current_village in villages:
          persons = Person.objects.all().filter(address=current_village)
          print "persons--" + str(persons)
          personsList.append(persons)  
    print "personsList--" + str(personsList)
    json_persons = serializers.serialize("json", personsList)
    print "json_persons--" + json_persons
    return HttpResponse(json_persons, mimetype="application/javascript")

It returns the following result on the terminal:

current_state--2
current_state--Odisha
districts--[<District: Jagatsighpur>, <District: Koraput>]
persons--[<Person: Annnn Ppppp>, <Person: Rrrrr Jeeee>, <Person: Raaaaa Jennn>, <Person: Annnnn Saaaa>]
persons--[<Person: Laaaa Sikaka>, <Person: Lingram  Azzzzz>]
personsList--[[<Person: Annnn Ppppp>, <Person: Rrrrr Jeeee>, <Person: Raaaaa Jennn>, <Person: Annnnn Saaaa>], [<Person: Laaaa Sikaka>, <Person: Lingram  Azzzzz>]]
**[15/Dec/2012 21:05:42] "GET /state/2/all_json_persons/ HTTP/1.1" 500 75201**

I am not able to figure out why the below line of code is not working in the above situation:

json_persons = serializers.serialize("json", personsList)

However, if I replace personsList in the above line with persons. It works good. But I want the entire list of persons in a state. Please help.

Upvotes: 0

Views: 345

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Django's serializers are for serializing querysets. If you want to serialize something else then convert it into a basic type with e.g. values() or values_list() and then use the normal JSON mechanism to serialize that.

Upvotes: 1

Related Questions