2013-12-12 82 views
0

我試圖以產生由指定的週數過去四周的圖表(按週週)cursor.fetchall多個查詢到一個列表

到目前爲止,我的模型和視圖的工作很好,我能查詢數據從原始數據庫 我也知道如何創建查詢4名名單:

results = [i for i in chain.from_iterable(cursor.fetchall())] 

[u'AAA', 191L, u'BBB', 21L, u'CCC', 420L, u'DDD', 150L, u'EEE', 759L, u'FFF', 290L, u'GGG', 166L, u'HHH', 8L, u'III', 1147L, u'JJJ', 1427L, u'KKK', 34L, u'LLL', 8L] 
[u'AAA', 191L, u'BBB', 21L, u'CCC', 420L, u'DDD', 150L, u'EEE', 759L, u'FFF', 290L, u'GGG', 166L, u'HHH', 8L, u'III', 1147L, u'JJJ', 1427L, u'KKK', 34L, u'LLL', 8L] 
[u'AAA', 191L, u'BBB', 21L, u'CCC', 420L, u'DDD', 150L, u'EEE', 759L, u'FFF', 290L, u'GGG', 166L, u'HHH', 8L, u'III', 1147L, u'JJJ', 1427L, u'KKK', 34L, u'LLL', 8L] 
[u'AAA', 191L, u'BBB', 21L, u'CCC', 420L, u'DDD', 150L, u'EEE', 759L, u'FFF', 290L, u'GGG', 166L, u'HHH', 8L, u'III', 1147L, u'JJJ', 1427L, u'KKK', 34L, u'LLL', 8L] 

,但我仍然無法從該四個列表合併一個列表,在結束列表看起來應該是如下:

[["ZZZ", "AAA", "BBB", "CCC"], ["48", 21, 223, 232], ["47", 334, 343, 232], ["46", 345, 542, 245], ["45", 764, 463, 989]] 

其中: ZZZ =週數 「48」, 「47」, 「46」, 「45」 AAA,BBB,CCC .... =從查詢

任何建議的名字?

我的models.py

def four_weeks(year, week): 
    end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU) 
    start = end - relativedelta(weeks=4, weekday=MO) 
    mint, maxt = datetime.min.time(), datetime.max.time() 
    for dt in rrule(WEEKLY, start, count=4): 
     yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt) 

views.py

def WeekCombo(request): 
    fweeks = [] 
    year = 2013 #this is only for test 
    week = 48 #in future it will be integrated with form 
    cursor = connections['mydba'].cursor() 
    for start, end in four_weeks(year, week): 
     cursor.execute("SELECT DISTINCT (p.name) AS platform, count(e.id) AS count FROM event e, lu_platform p WHERE e.platform_id = p.id AND e.sourcetype_id = 1 AND e.event_datetime BETWEEN %s AND %s AND e.sender_id NOT IN (759, 73) GROUP BY p.name ORDER BY p.name", [start, end]) 
     results = [i for i in chain.from_iterable(cursor.fetchall())] 
     fweeks.append(results) 
    return render_to_response('form.html', {'fweeks': fweeks}, context_instance=RequestContext(request)) 
+0

聽起來像是要合併所產生的名單。 http://stackoverflow.com/questions/1720421/merge-two-lists-in-python –

+1

這不完全清楚你的問題是什麼。你想將結果合併爲字典嗎? {'AAA':(17L,44L,76L),'BBB':(21L,96L,225L,304L)....? – Mzzl

+0

爲什麼你不使用django模型? – scriptmonster

回答

0

聽起來像是要合併所產生的名單。

How to append list to second list (concatenate lists)

您可以創建一個空表,每個查詢一步一步的結果擴展它。

如果你想先運行所有的查詢和合並列表之後使用itertools.chain

>>> listoflists = [['a'], ['b', 'c'], ['d', 'e', 'f']] 
>>> [i for i in itertools.chain.from_iterable(listoflists)] 
['a', 'b', 'c', 'd', 'e', 'f']