6

Since django 2.2 docs recommend to use UniqueConstraint instead of unique_together, but this option didn't raise ValidationError in django admin without overriding clean or validate_unique methods if condition attribute provided.

Is it possible to make UniqueConstraint raise ValidationError(in django admin) instead of IntegrityError without implementing validation logic by myself?

Max
  • 1,634
  • 1
  • 19
  • 36

1 Answers1

6

You're right that the documentation was misleading here. It said that:

UniqueConstraints are different in this regard, in that they leverage the existing validate_unique() logic, and thus enable two-stage validation.

What it didn't say is that that doesn't apply if you use the condition parameter. In response to your question I added a comment on the relevant issue to suggest that this be added to the documentation, and it was.

UniqueConstraints without a condition (i.e. non-partial unique constraints) are different in this regard...

According to this pull request comment, the reason this isn't implemented is that... it's hard.

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.

Of course, as you said, you can always override validate_unique() yourself.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • 1
    Thanks for this answer. validate_unique is indeed the way to go as of v3.x. One point to highlight is that Django automatically adds all fields of the model which are not in the form to the exclude list. Depending on your design, you might want to filter this to add/remove certain fields before calling the base class implementation. – Hari Mahadevan Dec 08 '20 at 03:49