Is there an easy way to create derived attributes in Django Model/Python classes?
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 co开发者_StackOverflowrresponding 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)
You've got two options I can think of right now:
- Since you don't want the field in the database your best bet is to define a method on the model that returns self.id * SOME_CONSTANT, say you call it big_id(). You can access this method anytime as yourObj.big_id(), and it will be available in templates as yourObj.big_id (you might want to read about the "magic dot" in django templates).
- If you don't mind it being in the DB, you can override the save method on your object to calculate id * SOME_CONSTANT and store it in a big_id field. This would save you from having to calculate it every time, since I assume ID isn't going to change
精彩评论