Search code examples
pythondjangodatabaseprimary-keyhashids

Getting Primary Key from database (Python / Django)


I'm trying to use Hashids which works when I manually input the number to encode, but doesn't work if I try to get it to encode the Primary Key from each table row.

models.py

from hashids import Hashids
from django.db import models

class AddToDatabase(models.Model):

    hashids = Hashids()
                                  # hasids.encode(123) works correctly
    slug = models.CharField(default=hashids.encode(pk), max_length=12)

The above says pk is undefined, regardless of what I try to import.


Solution

  • You cannot do what you are trying now(Since pk will get value only after INSERT operation). One option is

    class AddToDatabase(models.Model):
        hashids = Hashids()
        slug = models.CharField(max_length=12)
    
        def save(self, *args, **kwargs):
            super(AddToDatabase, self).save(*args, **kwargs)
            self.slug = self.hashids.encode(self.pk)
            super(AddToDatabase, self).save(*args, **kwargs)