Reputation: 17
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
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
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
Reputation: 265
Make your topic_id intergerfield
In def save():
self.topic_id = self.id
Upvotes: 0