Django infer a field from other fields

北战南征 提交于 2021-01-29 08:00:38

问题


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.


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/8326109/django-infer-a-field-from-other-fields

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