我有两个Django Querysets,我想根据它的日期atrribute合并。嗯,这不是真正的Django问题,但我试着尽可能清楚地解释 我需要根据两个数据属性对条目进行分组。可以说我有一个模型:
class User(models.Model):
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
...
现在我需要按月对这些条目进行分组(2010年5月开始的用户数等):
truncate_start_date = connection.ops.date_trunc_sql('month', 'start_date')
report_start = User.objects.exclude(start_date__isnull=True)\
.extra({'month': truncate_start_date}).values('month')\
.annotate(start_count=Count('pk')).order_by('-month')
我对end_date
的查询相同:
truncate_end_date = connection.ops.date_trunc_sql('month', 'end_date')
report_end = Employee.objects.exclude(end_date__isnull=True)\
.extra({'month': truncate_end_date}).values('month')\
.annotate(end_count=Count('pk')).order_by('-month')
现在这就是report_start
的样子:
[{'start_count': 33, 'month': datetime.datetime(2016, 5, 1, 0, 0, tzinfo=<UTC>)},
{'start_count': 79, 'month': datetime.datetime(2016, 4, 1, 0, 0, tzinfo=<UTC>)},
{'start_count': 72, 'month': datetime.datetime(2016, 3, 1, 0, 0, tzinfo=<UTC>)},
... ]
现在,如何基于month
将这两个dicts列表合并为一个?我尝试了chain
,但有重复的month
条记录
我想得到:
[{'start_count': 33, 'end_count': None, 'month': datetime.datetime(2016, 5, 1, 0, 0, tzinfo=<UTC>)},
{'start_count': 79, 'end_count': 2, 'month': datetime.datetime(2016, 4, 1, 0, 0, tzinfo=<UTC>)},
{'start_count': 72, 'end_count': 8, 'month': datetime.datetime(2016, 3, 1, 0, 0, tzinfo=<UTC>)},
... ]
我能想到的是将其改为dict然后再回到dicts列表。但我相信这不是一个非常优雅的解决方案,必须有更好的方法来编写这种pythonic方式 有任何想法吗?这是我丑陋的代码:
d = dict()
for end in report_end:
d[end['month']] = {"end_count": end['end_count']}
for start in report_start:
if start['month'] in d.keys():
d[start['month']]["start_count"] = start['start_count']
else:
d[start['month']] = {"start_count": start['start_count']}
result = []
for key, i in d.items():
result.append({'month': key,
'start_count': i['start_count'] if 'start_count' in i.keys() else None,
'end_count': i['end_count'] if 'end_count' in i.keys() else None})
答案 0 :(得分:1)
datetime
是可清除的,因此您可以将其存储为dict
的密钥并轻松合并。这是使用itemgetter
的一个简单的解决方案。这假定您的时间戳在每个dict
列表中都是唯一的。
from operator import itemgetter
import datetime
starts = [
{'start_count': 33, 'month': datetime.datetime(2016, 5, 1, 0, 0)},
{'start_count': 79, 'month': datetime.datetime(2016, 4, 1, 0, 0)},
{'start_count': 72, 'month': datetime.datetime(2016, 3, 1, 0, 0)}
]
# dummy data
ends = [
{'end_count': 122, 'month': datetime.datetime(2016, 5, 1, 0, 0)},
{'end_count': 213, 'month': datetime.datetime(2016, 4, 1, 0, 0)},
{'end_count': 121, 'month': datetime.datetime(2016, 3, 1, 0, 0)}
]
starts = dict(map(itemgetter('month', 'start_count'), starts))
ends = dict(map(itemgetter('month', 'end_count'), ends))
joined = [{'month': m, 'start_count': s, 'end_count': ends.get(m, None)}
for m, s in starts.items()]