Home > Mobile >  Django/Python: Merge same type of filter calls?
Django/Python: Merge same type of filter calls?

Time:04-22

I've got this code:


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,
        }

And as you can see I'm pretty much doing the same thing 4 times, just that in the end I filter for a different type of Action. So I wanted to improve my queries and was wondering if there is a clever solution for doing things like that, which is also more performant?

Thanks for any answers!

CodePudding user response:

You can fetch all results in a single query and then use itertools.groupby to group them by the 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)}
}
  • Related