0

I'm working on a game server matchmaking and I have a room object which has a range that has two field and other extra fields :

min_score = IntegerField (help = 'minimum score that user should have to join this room.')
max_score = IntegerField (help = 'maximum score that a user can have to join this room.')

I'm going to cache this object and then if a user requests to join a room with a range that users can join. Is there a way that I can do something like below query on redis-cache?

Room.objects.filter(min_score__lte=user.score, max_score__gte=user.score)

I already have some algorithms that should do .get('key') n times. But I wonder if there's a better solution.

Wasi
  • 1,473
  • 3
  • 16
  • 32
ArminMz
  • 325
  • 6
  • 9

1 Answers1

0

You can split this up in two filters, like:

Room.objects.filter(min_score__lte=user.score, max_score__gte=user.score)

We thus specify that the min_score is smaller than or equal to user.score, and the max_score is greater than or equal to user.score.

Here we use the __lte [Django-doc] and __gte lookups [Django-doc]. You can use __lt [Django-doc] and __gt [Django-doc] if you want the ranges to be exclusive.

By using a db_index, you probably can boost the lookup a bit more:

from django.db import models

class Room(models.Model):
    min_score = models.IntegerField(db_index=True)
    max_score = models.IntegerField(db_index=True)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • As I mentioned on the question I would like to cache this object by django-redis cache and I don't want it to be on my db. So I can't run queries with objects like Room.objects.filter(...) and I can just use cache methods like cache.get('key') but I can use your response to make my question more clear. – ArminMz Aug 10 '19 at 13:46