基于其他领域的模型领域?

编程入门 行业动态 更新时间:2024-10-25 07:25:19
本文介绍了基于其他领域的模型领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以有一个基于其他字段的模型字段吗?例如:

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.

此处的更多信息:官方文档

更多推荐

基于其他领域的模型领域?

本文发布于:2023-11-25 13:47:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:领域   模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!