Django:创建一个具有相同模型的(django 生成的)主键值的字段

Django : creating a field having the value of the (django-generated ) primary key of the same model

我正在尝试创建一个等于 Django 生成的主键值 (id) 的整数字段 (topic_id)。

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    topic_id = ?????

谢谢你的时间。

将其声明为一个方法并使用@属性装饰器将其return作为一个实际的属性。

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    @property
    def topic_id(self):
        return self.id

制作你的 topic_id intergerfield

在 def save() 中:

self.topic_id = self.id

您可以使用解决方案 here:

使 topic_id 成为 id 的别名
class AliasField(models.Field):
    def contribute_to_class(self, cls, name, private_only=False):
        super(AliasField, self).contribute_to_class(cls, name, private_only=True)
        setattr(cls, name, self)

    def __get__(self, instance, instance_type=None):
        return getattr(instance, self.db_column)

class Topic(models.Model):
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    topic_id = AliasField(db_column='id')