#34871: Validation of UniqueConstraint with Case() crashes.
-------------------------------------+-------------------------------------
     Reporter:  Andrew Roberts       |                    Owner:  Francesco
                                     |  Panico
         Type:  Bug                  |                   Status:  assigned
    Component:  Database layer       |                  Version:  4.2
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:  Accepted
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):

 I would suggest using a `Func` instead of `Case` / `When` or `Q` if you
 really need to achieve the exact SQL that `CASE WHEN` would generated

 Something like

 {{{#!python
 models.UniqueConstraint(
     Func(F("email")), template="CASE WHEN active = true THEN
 %(expressions)s END"),
     name="unique_active_email",
 )
 }}}

 Or to simply use `UniqueConstraint.condition` as
 [https://docs.djangoproject.com/en/5.0/ref/models/constraints/#condition
 documented] if the backend you use support it which will also incur less
 storage use.

 {{{#!python
 models.UniqueConstraint(
     fields=["email"],
     name="unique_active_email",
     condition=Q(active=True),
 )
 }}}

 I think we should spend the time to implement `Q.replace_expressions`
 though as it's pretty trivial to do so and would cover for the cases that
 cannot be expressed using `.condition` such as `CASE WHEN last_name IS
 NULL THEN first_name ELSE first_name || last_name END`.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/34871#comment:9>
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/0107018dcf356ce6-9a3c6b41-950c-433d-b9b7-dbbed6fa6cb1-000000%40eu-central-1.amazonses.com.

Reply via email to