Implement hashid in django

I am trying to implement hashids in django models. I want to get hashid based on the model id, for example, in the model id=3, then the hash coding should be: hashid.encode(id). The thing is, I cannot get id or pk until I save them. What I have in mind is to get the latest objects idand add 1to them. But this is not a solution for me. Can someone help me figure this out?

Django model:

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
source share
2 answers

, , , . , 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']) 
+1

, hashids id. ( ).

, hashid , :

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

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

( , , !)

0

Source: https://habr.com/ru/post/1652103/


All Articles