django模型是:
from hashids import hashidshashids = 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,**kwargs)解决方法 如果还没有ID,我只会告诉它保存,所以它不会每次运行代码.您可以使用TimeStampedModel继承来执行此 *** 作,这实际上非常适合在任何项目中使用.
from hashids import hashidshashids = 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,**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,**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'])总结
以上是内存溢出为你收集整理的python – 在django中实现hashid全部内容,希望文章能够帮你解决python – 在django中实现hashid所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)