Django Get ID of the object in save()

雨燕双飞 提交于 2021-02-10 07:10:36

问题


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?


回答1:


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 = obj.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 = obj.id + num
        self.save()

I hope this helps.



来源:https://stackoverflow.com/questions/16753219/django-get-id-of-the-object-in-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!