django - 有没有办法在 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
时间。但我想知道是否有更好的解决方案。
解决方案
您可以将其拆分为两个过滤器,例如:
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)
推荐阅读
- angular - 角度 12 中没有重载匹配此调用
- node.js - Node.js 说函数不是函数
- python - 如何比较 5 个不同的数组并根据每个索引中相同值的数量创建一个新数组
- python - 如何使用 2 个条件列基于其他数据框将列添加到 Pandas 中的数据框中?
- c - 卡在重新散列我在 C 中使用 Hashtable 实现的字典
- php - 将 Mysql 中的数据显示为有序列表
- mongodb - 如何在与 MongoDB 中的特定过滤器匹配的数组元素上创建索引?
- python - __init__() 接受 1 个位置参数,但给定 2 个类型错误
- python - opencv imread 在浏览器上返回 Nonetype(本地主机 Web 开发)
- python - 如何计算列表中的整数范围