在django中按名称分组查询元素

时间:2017-07-28 16:09:55

标签: django

我坚持这个任务。我的查询输出如下(当使用list()时):

days=[{'day':1,'do':'paint'},{'day':2,'do':'paint'},{'day':3,'do':'Dry'},{'day':4,'do':'Fubrish'},{'day':5,'do':'Fubrish'},{'day':6,'do':'paint'}]

它来自这个模型:

class Tasks(models.Model):

   day_no = models.IntegerField(verbose_name='Number of Day')  # 1, 2, 3, 4, 5, 6
   task = models.CharField(max_length=25)

我基本上想要循环遍历每个并查看是否连续存在“do”并存储已发现的总数。例如。第1天和第2天,建议用户进行绘画。第3天他做干燥,接下来的两天去Fubrish然后再画画。

我想要一个基本上会说:

的输出
paint: 2
dry: 1
fubrish: 2
paint: 1

我确实在我的jupyter上玩,但这是错误的:

tasks={}

total=len(days)

for i in range(0,total):
    day = days[i]['day']
    do = days[i]['do']

if i == 0:
    tasks[do]=1
else:
    if i+1 < total:
        if days[i+1]['do'] == do:  # the next one is same as current one
            tasks[do] = len(tasks) + 1
        else:
            if tasks.get(do, None) != None:
                tasks[do] = len(tasks) + 1
            else:
                tasks = {}
                tasks[do] = 1

3 个答案:

答案 0 :(得分:1)

您可以使用此功能:

this

答案 1 :(得分:1)

它适用于您的要求。

    from itertools import groupby

    data = [{'grouper': key, 'list': list(group)} for key, group in groupby(queryset, lambda x: getattr(x, 'do')
    for d in data:
        print d['grouper'], len(d['list')

queryset 传递给上面这一行,并在最后编辑字段名称。它将输出为 django templatetag {%regroup%}标记https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#regroup

答案 2 :(得分:0)

您还可以使用下面的defaultdict和代码:

from collections import defaultdict
results = []
prev_task = defaultdict(int)
for d in days:
    curr_task = d['do']
    if curr_task not in prev_task and len(prev_task) > 0:
        results.append(dict(prev_task))
        prev_task.clear()
    prev_task[curr_task] += 1
    if d is days[-1]:
        # if this is the last item
        results.append(dict(prev_task))