本文介绍了基于其他领域的模型领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以有一个基于其他字段的模型字段吗?例如:
Can I have a model field be based on other fields? For example:
class Foo(models.Model): x = models.PositiveSmallIntegerField() y = models.PositiveSmallIntegerField() z = models.PositiveSmallIntegerField() score = models.PositiveSmallIntegerField(default=x+y+z)推荐答案
是的,处理此问题的最佳方法是覆盖保存模型的方法
Yes, the best way to handle this would be to override the save method of the model
class Foo(models.Model): x = models.PositiveSmallIntegerField() y = models.PositiveSmallIntegerField() z = models.PositiveSmallIntegerField() score = models.PositiveSmallIntegerField() def save(self, *args, **kwargs): self.score = self.x + self.y + self.z super(Foo, self).save(*args, **kwargs) # Call the "real" save() method.请确保您已做好必要的验证工作。
Make sure you take care of the necessary validations.
此处的更多信息:官方文档
更多推荐
基于其他领域的模型领域?
发布评论