简体   繁体   中英

Django set model value, using another value of the same model

I am creating a board game, and I want to set value job_exp using an age value, I tried to use redefined save method, but it changes value after each save,so I try to create method, but I got:

TypeError: unsupported operand type(s) for -: 'IntegerField' and 'int'

Here is models:

class Character(models.Model):
    def set_job_exp(age):
        return randint(0, age - 18)

    age = models.IntegerField("Age",default=randint(18, 100))
    job_exp = models.IntegerField('Job exp',blank=True,default=set_job_exp(age)

How to convert IntegerField to int or do you have any ideas how to solve it?

You can do it by redefining.save() method for cases like this. Here you can check if an instance does not have a pk value then it is a new instance and about to be created.

def save(self, *args, **kwargs):
    if not self.pk:
        self.job_exp = randint(0, self.age - 18)
    super().save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM