我有這個代碼:
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 次相同的事情,只是最后我過濾了不同型別的動作。所以我想改進我的查詢,并想知道是否有一個聰明的解決方案來做這樣的事情,它也更高效?
感謝您的任何回答!
uj5u.com熱心網友回復:
您可以在單個查詢中獲取所有結果,然后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)}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/464451.html
上一篇:按日期獲取記錄是30天的倍數
