ModelForm uniqueness checks

As I understand it, a ModelForm for a model with a unique field will query the database to do a uniqueness check in the validation step, outside of the database uniqueness enforcement. Is that accurate?

If so, is the reason for this to have all the validation in the form? Or are there other reasons to do the validation in the form and then have the database enforce uniqueness again?

Are there any concerns about race conditions, where a form validates properly, but then the save call fails because a duplicate record was inserted in the meantime?

I remember thinking about this myself once and I suspect the answer is that it’s tricky to turn a database error back into a form validation error, so we check explicitly in the validation layer. This way most of the time the user gets the nice validation error, but occasionally the race you mention happens and the error is worse.

From a purity point of view, I think trying the save and then if it fails turning the error back into a nice form validation would be nice. From a pragmatic point of view, the status quo is usually good enough.

2 Likes