Home > other >  Django how to add a field to a model that relies on the pk being created first
Django how to add a field to a model that relies on the pk being created first

Time:09-07

I am trying to add a hashid that is based on the pk of my model

class ExampleModel(models.Model):
    hash_id = models.CharField(max_length=30)

How the hash_id is created.. Assume 15454 is the pk of my object.

from hashids import Hashids
hashids = Hashids(salt='example salt')
hashids.encode(15454)
'Eo6v'

The main reason I want to store the hash_id in the model is because I don't want to recompute it everytime or if my salt changes in the future for some reason.

Is there a way to automatically generate this field when the object is created since it needs the PK to be created first?

CodePudding user response:

How about to override in save model? like:

class ExampleModel(models.Model):
    hash_id = models.CharField(max_length=30)

    def save(self, *args, **kwargs):
        is_create = self.pk is None
        super().save(*args, **kwargs)

        # We got pk after save above.
        if is_create:
            hashids = Hashids(salt='example salt')
            self.hash_id = hashids.encode(self.pk)
            super().save(update_fields=["hash_id"])
            
 
  • Related