简体   繁体   中英

Django infer a field from other fields

I am currently having a model:

class Current(models.Model):  
    field1 = models.IntegerField()  
    field2 = models.IntegerField()
    field3 = models.IntegerField()  

I need to have field3 to be set directly equal to field1 + field2 without actually sending it.
What's the standard way in django to do this?

PS: Yes, I need to save field3 in the database alongwith the other fields.

Something like this? But not sure why this would need to be saved in the database.

class Current(models.Model):  
    field1 = models.IntegerField()  
    field2 = models.IntegerField()
    field3 = models.IntegerField()  

    def save(self, *args, **kwargs):
        self.field3 = self.field1 + self.field2
        super(Current, self).save(*args, **kwargs)

You can overwrite the model's save() method. But why do you need to save field3 at all?

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