2014-02-10 50 views
1

我View.py:如何將ValueQuryset的值追加到數組中?

from django.db.models import Count 
def test1(request): 
    states = Loksabha.objects.values('state').distinct('state') 
    terms = Loksabha.objects.values('term').distinct('term') 
    dataset = Loksabha.objects.all() 
    state_filter=Loksabha.objects.filter(state='Maharashtra',term='Fourteenth Lok Sabha(2004- 09)').annotate(num=Count('party',distinct=True)) 
    age_filter=state_filter.values('party').annotate(Count('party')) 
    xdata=[] 
    ydata=[] 
    for b in state_filter: 
     xdata.append(b.party) 
     ydata.append(b.num) 
    chartdata = {'x': xdata, 'y': ydata} 
    charttype = "pieChart" 
    chartcontainer = 'piechart_container' 

我已經使用Django的nvd3顯示圖形我state_filter查詢的答案是coreect,但我不能瞭解ValueQueryset的值傳遞給xdata[]ydata[]。我state_filter查詢集值傳遞給age_filter

age_filter值:

[{'party': 'Shiv Sena', 'party__count': 14}, 
{'party': 'Indian Nationlist Congress', 'party__count': 15}, 
{'party': 'Nationlist Congress Party', 'party__count': 9}, 
{'party': 'Republican Party of India(A)', 'party__count': 1}, 
{'party': 'Bharatiya Janata Party', 'party__count': 14}, 
{'party': 'Independent', 'party__count': 1}] 

回答

3

ValueQuerySet產生字典。通過索引獲取項目,而不是訪問屬性。

替換以下行:

for b in state_filter: 
    xdata.append(b.party) 
    ydata.append(b.num) 

有:

for d in age_filter: 
    xdata.append(b['party']) 
    ydata.append(b['party_count']) 
+0

感謝falsetru哥哥 – pramod24

+0

大!!!!!!!!!!! –

相關問題