从数据库获取主键(Python / Django)

Getting Primary Key from database (Python / Django)

我正在尝试使用 Hashids,当我手动输入要编码的数字时它可以工作,但如果我试图让它对每个 table 的主键进行编码则不起作用行。

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)

上面说 pk 是未定义的,不管我尝试导入什么。

你不能做你现在正在尝试的事情(因为 pk 只有在 INSERT 操作后才能获得价值)。一种选择是

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)

另一种解决方案是按需计算hashid

class AddToDatabase(models.Model):

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