有没有一种方法可以查询Django Redis缓存中基于范围的键缓存对象?

时间:2019-08-10 13:03:59

标签: django caching django-rest-framework django-cache redis-cache

我正在做一个游戏服务器对接会,我有一个房间对象,该对象的范围包含两个字段和其他多余的字段:

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.')

我要缓存该对象,然后如果用户请求加入一个用户可以加入的范围的房间。 有什么办法可以在redis-cache上执行以下查询吗?

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

我已经有一些算法应该执行.get('key') n次。 但我想知道是否有更好的解决方案。

1 个答案:

答案 0 :(得分:0)

您可以将其分为两个过滤器,例如:

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

因此,我们指定min_score小于或等于user.score,并且max_score大于或等于user.score

在这里我们使用__lte [Django-doc]__gte lookups [Django-doc]。如果您希望范围互斥,则可以使用__lt [Django-doc]__gt [Django-doc]

通过使用db_index,您可能可以进一步提高查找速度:

from django.db import models

class Room(models.Model):
    min_score = models.IntegerField(db_index=True)
    max_score = models.IntegerField(db_index=True)