首页 > 解决方案 > 有没有办法在 django redis 缓存中查询基于范围的键缓存对象?

问题描述

我正在做一个游戏服务器匹配,我有一个房间对象,它的范围有两个字段和其他额外字段:

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时间。但我想知道是否有更好的解决方案。

标签: djangocachingdjango-rest-frameworkdjango-cacheredis-cache

解决方案


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

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查找 [Django-doc]。如果您希望范围是独占的,您可以使用__lt[Django-doc]__gt[Django-doc] 。

通过使用 a 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)

推荐阅读