Liam
Liam

Reputation: 65

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.

Upvotes: 1

Views: 923

Answers (2)

aliva
aliva

Reputation: 5720

Another solution is calculating hashid on demand

class AddToDatabase(models.Model):

    @property
    def slug(self):
        hashids = Hashids()
        return hashids.encode(self.pk)

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20339

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)

Upvotes: 1

Related Questions