【发布时间】:2019-11-08 04:01:10
【问题描述】:
我有一个带有 1 个主键和 3 个字段的简单模型(简化):
- 及格分数
- 最高分
- 最大尝试次数
此模型是通过继承 django.db.models 创建的。这是最小的可重现代码:
from django.db import models
class QuestionSet(models.Model):
passingscore = models.PositiveSmallIntegerField("passing score")
maxscore = models.PositiveSmallIntegerField("max score")
maxattempt = models.PositiveSmallIntegerField("max attempt")
我想添加一个约束,使passingscore 在数据库中永远不会大于maxscore。
根据this thread on StackOverflow,我使用了跨越多个字段的约束,例如unique_together。但显然这是一个不同的用例。
我也简单考虑过直接写PostgreSQL代码加约束:
ALTER TABLE tableB ADD CONSTRAINT score_policy_1 CHECK (maxscore >= passingscore)
但这违背了使用 ORM 的目的,违反了“松散耦合”的理念,使得在不同的数据库后端之间迁移变得困难。
如果这是可能的,请指出在 Django 中编写此约束的更惯用的方式。
【问题讨论】:
-
@cwhisperer 实际上不是。元约束是我知道并充分利用的东西,但是没有描述或说明对受值或其他字段约束的约束。不过谢谢!
标签: python django database django-models