【问题标题】:Implement hashid in django在 django 中实现 hashid
【发布时间】: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) 

【问题讨论】:

    标签: python django hashids


    【解决方案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']) 
    

    【讨论】:

    • 这个在保存后没有创建 hashid
    • 您是通过命令行创建文章吗?该方法在创建模型实例时不运行“save()”方法。
    • 不,我通过管理面板创建了文章。是不是因为修改日期和创建日期不相等???
    • 在对象保存时调用 Python 对象时,它还给我超出了最大递归深度
    【解决方案2】:

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

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

    instance = Article()
    instance.title = 'whatever...'
    instance.text = 'whatever...'
    instance.save()
    
    hashids = Hashids()    
    instance.hashid = hashids.encode(instance.id)
    instance.save()
    

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

    【讨论】:

    • 从观点来看这是一个不错的方法
    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2021-10-19
    • 2019-10-10
    • 2016-08-24
    相关资源
    最近更新 更多