2012-12-16 42 views
0

我在views.py中有以下代碼,我想要得到一個人的完整列表。Django - JSON serializers.serialize不工作

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

它返回終端上做如下結果:

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

我無法找出原因的代碼下面的行未在上述情況下工作:

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

但是,如果我將以上人員中的personsList替換爲人員。它運作良好。但我想要一個州的整個人名單。請幫忙。

+0

您應該閱讀手冊中的[後續關係](https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward)。 –

回答

1

Django的序列化器用於序列化查詢集。如果你想序列化別的東西,然後把它轉換成一個基本類型,例如values()values_list(),然後使用正常的JSON機制將其序列化。

+0

謝謝。我更改爲下面,它的工作原理:對於current_village在村: persons = Person.objects.all()。filter(address = current_village) for p: personsList.append(p.id) personsListQset = Person。 objects.filter(pk__in = personsList) json_persons = serializers.serialize(「json」,personsListQset) – Gunjan