cursor.fetchall对一个列表的多个查询

时间:2013-12-12 12:58:09

标签: python django

我尝试从指定的周数(逐周)生成过去四周的图表

到目前为止,我有模型和视图工作正常,我能够从原始数据库查询数据 我也知道如何从查询中创建四个列表:

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 .... =来自查询的名称

任何建议?

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

1 个答案:

答案 0 :(得分: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']