joseph
joseph

Reputation: 17

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

I'm trying to create an integer field (topic_id) equal to the Django-generated primary key value (id).

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

Thx for your time.

Upvotes: 0

Views: 89

Answers (3)

blhsing
blhsing

Reputation: 106512

You can make topic_id an alias to id with the solution here:

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')

Upvotes: 1

gurpreet singh chahal
gurpreet singh chahal

Reputation: 370

Declare it as a method and use @property decorator to return it as an actual property.

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

Upvotes: 1

Learning Django
Learning Django

Reputation: 265

Make your topic_id intergerfield

In def save():

self.topic_id = self.id

Upvotes: 0

Related Questions