Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda