You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django 4.1+中UniqueConstraint为何未触发ValidationError?

Django 4.1+ 下UniqueConstraint未在模型验证阶段触发的问题

自Django 4.1起,约束应在模型验证阶段被检查。我原本期望通过标准CreateView(未使用自定义Form)创建违反UniqueConstraint的新条目时,会触发ValidationError,表单重新显示并附带错误提示——就像字段设置unique=True时的表现一样。但实际却抛出IntegrityError(导致500内部服务器错误),说明验证未执行,仅在数据库创建条目时才检测到约束违反。我是否操作有误?

模型代码

class Child(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)

    class Meta:
        indexes = [models.Index(fields=['name'])]
        constraints = [models.UniqueConstraint(fields=['name', 'parent'], name='unique_ChildName')]

旧版本不会这样处理,仅在特定情况下检查UniqueConstraint,此前已有相关讨论手动实现方案,但本问题针对Django 4.1+版本


编辑内容

根据建议,我已将parent字段添加到表单字段中。为使其不可修改,编写了如下Form:

表单代码

class ChildCreateForm(ModelForm):
    parent = ModelChoiceField(queryset=None, disabled=True, required=False)

    class Meta:
        model = Child
        fields = ['parent', 'name']

    def __init__(self, parent_id=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['parent'].queryset = Parent.objects.filter(pk=parent_id)
        self.fields['parent'].initial = parent_id

视图代码

form_class = ChildCreateForm
def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['parent_id'] = ... # 项目特定逻辑
    return kwargs

内容的提问来源于stack exchange,提问作者RobV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 21:05:01