【发布时间】:2016-08-22 19:03:43
【问题描述】:
我一直在尝试在 django 模型中实现 hashids。我想根据模型的id 获取哈希值,就像模型的id=3 一样,哈希编码应该是这样的:hashid.encode(id)。问题是在我保存它们之前我无法获得 id 或 pk。我的想法是获取最新的对象id 并在其上添加1。但这对我来说不是解决方案。谁能帮我弄明白???
django 模型是:
from hashids import Hashids
hashids = Hashids(salt='thismysalt', min_length=4)
class Article(models.Model):
title = models.CharField(...)
text = models.TextField(...)
hashid = models.CharField(...)
# i know that this is not a good solution. This is meant to be more clear understanding.
def save(self, *args, **kwargs):
super(Article, self).save(*args, **kwargs)
self.hashid = hashids.encode(self.id)
super(Article, self).save(*args, **kwargs)
【问题讨论】: