Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report

0

Another solution is calculating hashid on demand

class AddToDatabase(models.Model):

    @property
    def slug(self):
        hashids = Hashids()
        return hashids.encode(self.pk)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!