SULPHURIC ACID
SULPHURIC ACID

Reputation: 337

how to add string to primary key in django model

i want my id to be "ssid"+ (autoimcrement id) example: ssid001

this is my user model

class User(models.Model):
    id = models.AutoField(primary_key=True, editable=False, unique=True, max_length=99999) 
    phone = models.CharField(max_length=12, unique=True,default="") 
    name = models.CharField(max_length=50,default="")
    email = models.EmailField(max_length=50,default="")

Upvotes: 1

Views: 1063

Answers (1)

beasyx
beasyx

Reputation: 152

You can do something like this:

class User(AbstractUser):
    pub_id = models.CharField(editable=False, unique=True, max_length=50)

    def save(self, *args, **kwargs):
        '''
        --User model save method--
        if not self.id makes sure the save only runs on first save.
        '''
        if not self.id:
            self.pub_id = f'ssid00{self.id}'
        return super(User, self).save(*args, **kwargs)

Make sure you over ride the User model with AbstractUser before you do a migration for the first time or you could have problems. Inside the save you can perform any logic to add a new pub_id, I gave an example. I find that leaving the primary_key alone causes less issues for my project down the road so I always just put a new pub_id field. This new pub_id can be used for detail pages so you don't expose your sequential keys to the world.

For example in your front end template you could do this:

{% url 'user-detail' pub_id=user.pub_id %}

Instead of:

{% url 'user-detail' id=user.id %}

But that still shows your sequential keys so I would use uuid:

import uuid

class User(AbstractUser):
    pub_id = models.CharField(editable=False, unique=True, max_length=50)

    def save(self, *args, **kwargs):
        '''
        --User model save method--
        1) Sets self.pub_id to UUID hex on first save.
        '''
        if not self.id:
            self.pub_id = str(uuid.uuid4().hex)
        return super(User, self).save(*args, **kwargs)

Upvotes: 3

Related Questions