#30581: Allow constraints to be used for validation (in Python)
-------------------------------------+-------------------------------------
               Reporter:  Carlton    |          Owner:  nobody
  Gibson                             |
                   Type:  New        |         Status:  new
  feature                            |
              Component:  Database   |        Version:  2.2
  layer (models, ORM)                |       Keywords:  constraints,
               Severity:  Normal     |  validation
           Triage Stage:  Accepted   |      Has patch:  0
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 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.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/30581>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/056.e19bf2e6d5ed1819dc946e7751372bdb%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to