views:

134

answers:

3

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?

+1  A: 
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)
shanyu
+4  A: 

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.

shylent
thanks! properties are what i was looking for...
akv
A: 

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
Matt Baker