#35848: Problem with UniqueConstraint on fields, one of which allows NULL value.
-------------------------------------+-------------------------------------
     Reporter:  platonovap           |                     Type:  Bug
       Status:  new                  |                Component:
                                     |  Uncategorized
      Version:  5.1                  |                 Severity:  Normal
     Keywords:  UniqueConstraint,    |             Triage Stage:
  nullable, null                     |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
 UniqueConstraint does not work correctly for several fields, one of which
 is nullable.

 {{{
 class MyModel(models.Model):

     id = models.BigAutoField(primary_key=True, editable=False)
     name = models.CharField(max_length=1000, verbose_name="Name")
     measure = models.ForeignKey(
         Measure,
         related_name="mymodel_measure",
         on_delete=models.SET_NULL,
         null=True,
         blank=True,
         verbose_name="Measure",
     )


     class Meta:
         constraints = [
             models.UniqueConstraint(
                 fields=["name"],
                 name="mymodel_unique_name_measure_null",
                 condition=Q(measure__isnull=True),
                 violation_error_message="Error message for null",
             ),
             models.UniqueConstraint(
                 fields=["name", "measure"],
                 name="mymodel_unique_name_measure_not_null",
                 condition=Q(measure__isnull=False),
                 violation_error_message="Error message for not null",
             ),
         ]
 }}}

 Database  - Postgres 15.

 The error is as follows: if there is a record with the field measure = not
 null, you can create a new record with the same name and measure = null.
 And if there is an entry with measure = null, then a new entry with the
 same name and measure = not null does not work.

 From the Postgres side, Constraints are created and working correctly.

 Error message:
 {{{
 {
   "error": "{'name': [ErrorDetail(string='The name of the mymodel with
 this Name already exists.', code='unique')]}"
 }
 }}}
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35848>
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/0107019299129fff-5534f802-2267-4e66-882d-326ed42366a4-000000%40eu-central-1.amazonses.com.

Reply via email to