Goran
Goran

Reputation: 6824

Django Get ID of the object in save()

I have some fixed number let say it is num = 1000 Now I have field which need to be sum of the object.id and num. I need this in save() something like below.

def save(self, *args, **kwargs):
    num = 1000
    self.special = self.id + num
    super(MyModel, self).save(*args, **kwargs)

But self.id is known after save and field named special is required. How to get self.id?

Upvotes: 4

Views: 5131

Answers (1)

Paulo Bu
Paulo Bu

Reputation: 29794

First of all? Is the number you're trying to add a fixed number? If so, why do you have to store it in the db at all? You may create a method to your model that works as a property and adds the number when you need it:

class ModelX(models.Model):
    ...
    def special(self):
        num = 1000
        return self.id + num

If you really need to store this to the db you maybe need to do two database access because as Daniel said, you get the id after the object is stored in the db.

You may modify your save method to this one:

def save(self, *args, **kwargs):
    num = 1000
    self = super(MyModel, self).save(*args, **kwargs)
    self.special = self.id + num
    self.save()

Note that this may be optimized by just doing this the first time an object is created in the db, where self.special is NULL or default value depending on how you declared your model.

def save(self, *args, **kwargs):
    num = 1000
    self = super(MyModel, self).save(*args, **kwargs)
    # self.special is null, (creating the object in the db for the 1st time)
    if not self.special: # or if self.special != defaultvalue (defined in MyModel)
        self.special = self.id + num
        self.save()

I hope this helps.

Upvotes: 8

Related Questions