[英]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. 我需要将field3设置为直接等于field1 + field2而不实际发送它。
What's the standard way in django to do this? django做标准的标准方法是什么?
PS: Yes, I need to save field3 in the database alongwith the other fields. PS:是的,我需要将field3与其他字段一起保存在数据库中。
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. 您可以覆盖模型的save()方法。 But why do you need to save field3 at all? 但为什么你需要保存field3呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.