自 django 2.2 docs建议使用 UniqueConstraint 而不是 unique_together,但此选项不会在 django admin 中引发 ValidationError 而不覆盖 clean 或 validate_unique 方法,如果提供了 condition 属性。
是否可以让 UniqueConstraint 引发 ValidationError(在 django admin 中)而不是 IntegrityError 而无需我自己实现验证逻辑?
请您参考如下方法:
你是对的 documentation在这里误导了。它说:
UniqueConstraintsare different in this regard, in that they leverage the existingvalidate_unique()logic, and thus enable two-stage validation.
它没有说明的是,如果您使用 condition 参数,那将不适用。为了回答你的问题,我添加了一个 comment on the relevant issue建议将其添加到文档中,并且 it was .
UniqueConstraintswithout acondition(i.e. non-partial unique constraints) are different in this regard...
根据 this pull request comment ,未实现的原因是……这很难。
I feel like the appropriate solution is to completely ignore partial constraints for now... The current implementation is too naive... I suspect this will be complicated to support on all backends.
当然,正如您所说,您始终可以自己覆盖 validate_unique()。
