python - Can this be reduced to a single query? -
i have model field position = positiveintegerfield(unique=true)
. given instance of model, want instance next highest position (subject filters). if instance 1 highest position, want wrap around 0 , return instance lowest position; if instance one, want return itself.
here's code:
count = player.objects.count() return player.objects.filter(game_id=self.game_id, is_alive=true).annotate( relative_position=(f('position') - self.position - 1 + count) % count ).order_by('relative_position')[:1].get()
(the reason + count
because negative number modulo positive 1 negative in sql.)
this requires 2 database queries. suspect it's possible in 1 query, using annotate
, count
, haven't figured out how put such query together. can done, , if so, how?
not 1 query, beats 2 queries , annotations:
players = player.objects.filter(game_id=self.game_id, is_alive=true).order_by('position') try: return players.filter(position__lt=self.position)[0] except indexerror: return players.last()