﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
30581	Allow constraints to be used for validation (in Python)	Carlton Gibson	Gagaro	"Follow-up from #30547, where we documented how database constraints relate to validation. 

**Executive summary**: In general they don't. Instead you get an `IntegrityError` on `save()`. Except, `UniqueConstraint` is able to tie-in to the existing `validate_unique()` logic, so you will get a `ValidationError` on `full_clean()`.

It would be **nice** if all constraints could (in principle) be used for Python-level validation, in addition to setting up the database constraint. (We might image `ModelForm`, say, being able to extract correct validation logic from the model definition, and so on.) 

Initial thought is that Python validators could be inferred from `Q` objects: 

{{{
CheckConstraint(check=Q(age__gte=18), name='age_gte_18')
}}}

Looks like it maps to a simple `lambda age: age > 18`, for example. 

More complex examples will cause issues. Discussion: 

* [https://github.com/django/django/pull/10796#discussion_r244216763 PR #10796 (comment)]
* [https://github.com/django/django/pull/388#issuecomment-8863209 PR #388 (comment)]

So we **might** be able to do **some** auto-generation but first goal here should (I guess) be an optional hook on `BaseConstraint` that **if implemented** can be picked up for use in validation. (Or similar.)

I'll create this as Accepted, since existing discussions imply that. "	New feature	closed	Database layer (models, ORM)	4.0	Normal	fixed	constraints, validation	Simon Charette Adam Johnson Ian Foote Fabio Caritas Barrionuevo da Luz Gagaro	Ready for checkin	1	0	0	0	0	0
