python - 具有 IntegrityError 的 Django CheckConstraint

标签 python python-3.x django django-models

我想在我的 Django 模型中添加一个约束。我认为 CheckConstraint 方法有助于在输入不满足约束条件时捕获错误。但是,当我使用无效输入保存模型时,例如百分比 = 101,显示带有 IntegrityError 的错误页面。这里有人知道如何正确使用此方法来验证输入吗?

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(percentage__gte=1)
                & Q(percentage__lte=100),
                name="Please enter a valid percentage",
            )
        ]

解决方案: 我最终用它来解决我的问题

    def clean_fields(self, exclude=None):
        super().clean_fields(exclude=exclude)
        if self.percentage and (
            self.percentage < 0 or self.percentage > 100
        ):

最佳答案

约束(仅)在数据库端强制执行,因此当不满足给定条件时会导致IntegrityError

为了引发正确的验证错误,您将验证器添加到模型字段,例如:

from django.core import validators

class MyModel(models.Model):
    percentage = models.IntegerField(validators=[
        validators.MinValueValidator(1),
        validators.MaxValueValidator(100)
    )]

    # …

关于python - 具有 IntegrityError 的 Django CheckConstraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68646012/

相关文章:

python - 从 CherryPy 提供 css 文件

python - cx_freeze 后的 subprocess.Popen 行为

python - 检查FTP连接是否成功打开,文件是否已上传到Python中的FTP

python - Django 管理中的富文本编辑器 - 隐藏更改列表中的 HTML 标记

python - Django、Apache 和 session

python - 为什么我收到 IOError : [Errno 13] Permission denied?

python - 我可以相信 dict 的顺序在每次迭代时都保持不变吗?

Python - 未知大小的二维列表

python - 如何通过代码注册python3实例方法进行查找?

python - 为单元测试覆盖 auto_now