【问题标题】:Is there a way to query over a range based key cached object in django redis cache?有没有办法在 django redis 缓存中查询基于范围的键缓存对象?
【发布时间】:2019-12-17 22:11:18
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

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

Room.objects.filter(<b>min_score__lte=user.score, max_score__gte=user.score</b>)

因此我们指定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)

【讨论】:

  • 正如我在问题中提到的,我想通过 django-redis 缓存来缓存这个对象,我不希望它在我的数据库上。所以我不能对像 Room.objects.filter(...) 这样的对象运行查询,我可以只使用像 cache.get('key') 这样的缓存方法,但我可以使用你的回复来让我的问题更清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多