Django/Python: 合并相同类型的过滤器调用?
Django/Python: Merge same type of filter calls?
我有这个代码:
report = {
'period': {
'actions': [a.for_report() for a in team_actions.filter(type=Action.ACTION)],
'events': [e.for_report() for e in team_actions.filter(type=Action.EVENT)],
'timeskip': [t.for_report() for t in team_actions.filter(type=Action.TIMESKIP)],
'buysell': [b.for_report() for b in team_actions.filter(type=Action.BUYSELL)],
}
# This is what the for_report function does
def for_report(self):
return {
'name': self.name,
'value': self.value,
}
如您所见,我几乎将同一件事做了 4 次,只是最后我过滤了不同类型的操作。所以我想改进我的查询,想知道是否有一个聪明的解决方案来做这样的事情,而且性能更高?
感谢您的回答!
您可以在单个查询中获取所有结果,然后使用 itertools.groupby
按 type
对它们进行分组
keyfunc = lambda obj: obj.type
query = team_actions.order_by('type')
report = {
'period': {key: [x.for_report() for x in group] for key, group in itertools.groupby(query, keyfunc)}
}
我有这个代码:
report = {
'period': {
'actions': [a.for_report() for a in team_actions.filter(type=Action.ACTION)],
'events': [e.for_report() for e in team_actions.filter(type=Action.EVENT)],
'timeskip': [t.for_report() for t in team_actions.filter(type=Action.TIMESKIP)],
'buysell': [b.for_report() for b in team_actions.filter(type=Action.BUYSELL)],
}
# This is what the for_report function does
def for_report(self):
return {
'name': self.name,
'value': self.value,
}
如您所见,我几乎将同一件事做了 4 次,只是最后我过滤了不同类型的操作。所以我想改进我的查询,想知道是否有一个聪明的解决方案来做这样的事情,而且性能更高?
感谢您的回答!
您可以在单个查询中获取所有结果,然后使用 itertools.groupby
按 type
keyfunc = lambda obj: obj.type
query = team_actions.order_by('type')
report = {
'period': {key: [x.for_report() for x in group] for key, group in itertools.groupby(query, keyfunc)}
}