4

我一直在尝试在 django 模型中实现hashids 。我想根据模型获取 hashid,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) 
4

2 回答 2

1

如果还没有 ID,我只会告诉它保存,所以它不会每次都运行代码。您可以使用 TimeStampedModel 继承来做到这一点,这实际上非常适合在任何项目中使用。

from hashids import Hashids


hashids = Hashids(salt='thismysalt', min_length=4)


class TimeStampedModel(models.Model):
    """ Provides timestamps wherever it is subclassed """
    created = models.DateTimeField(editable=False)
    modified = models.DateTimeField()

    def save(self, *args, **kwargs):  # On `save()`, update timestamps
        if not self.created:
            self.created = timezone.now()
        self.modified = timezone.now()
        return super().save(*args, **kwargs)

    class Meta:
        abstract = True  


class Article(TimeStampedModel):
    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)
        if self.created == self.modified:  # Only run the first time instance is created (where created & modified will be the same)
            self.hashid = hashids.encode(self.id)
            self.save(update_fields=['hashid']) 
于 2016-08-22T19:07:04.473 回答
0

我认为 hashids 总是为特定的 id 返回相同的值。所以你可以在显示它之前计算它(使用模板标签)。

但是如果你仍然想保存它,一种方法是在视图中保存 hashid 字段,如下所示:

instance = Article()
instance.title = 'whatever...'
instance.text = 'whatever...'
instance.save()

hashids = Hashids()    
instance.hashid = hashids.encode(instance.id)
instance.save()

(我不知道这是否是最好的方法,但它对我有用!)

于 2017-07-05T05:19:42.333 回答