我应该如何生成缓存键

How should I generate cache keys

我想为每个问题缓存以下模型和缩短的link。

class Question(models.Model):
    question_text = models.CharField('text', max_length=200)
    pub_date = models.DateTimeField('publication date', default=timezone.now)
    allow_multiple_choices = models.BooleanField(default=False)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField('text', max_length=200)
    votes = models.IntegerField('votes', default=0)

    def __str__(self):
        return self.choice_text

我应该如何生成密钥?这样就够了吗?

cache.set('question' + question.id, question)
cache.set('shortened' + question.id, shortened)

这应该可以。但不确定所创建实例的范围。如果它们是全局的,我们保证键不重叠。

来自 id

的文档

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

也许您应该尝试其他方法,这可以保证您的集合的键唯一并且分布均匀。 在我们的实现中,我们将从实例标识数据生成一些哈希码(md5 或 sha1)。