Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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:

  1. 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).
  2. 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top