Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 corresponding database table having a column called big_id.

Is this possible?

like image 688
akv Avatar asked Jan 23 '23 02:01

akv


2 Answers

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.

like image 194
shylent Avatar answered Jan 25 '23 16:01

shylent


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)  
like image 37
shanyu Avatar answered Jan 25 '23 16:01

shanyu