我一直在努力在
django模型中实现
hashids.我想基于模型的id获取hashid,比如当模型的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)
最佳答案 如果还没有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'])