Every Django model has a default primary-key id
created automatically. I want the model objects to have another attribute big_id
which is calculated as:big_id = id * SOME_CONSTANT
I want to access big_id
as model_obj.big_id
without the corresponding database table having a column called big_id
.
Is this possible?
Well, django model instances are just python objects, or so I've been told anyway :P
That is how I would do it:
class MyModel(models.Model):
CONSTANT = 1234
id = models.AutoField(primary_key=True) # not really needed, but hey
@property
def big_id(self):
return self.pk * MyModel.CONSTANT
Obviously, you will get an exception if you try to do it with an unsaved model. You can also precalculate the big_id value instead of calculating it every time it is accessed.
class Person(models.Model):
x = 5
name = ..
email = ..
def _get_y(self):
if self.id:
return x * self.id
return None
y = property(_get_y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With