Hello,
First of all, you've being doing a great work here. Django is an amazing 
framework!

I have been woking in a new project and I need to do a multiple columns 
unique validation in which some of them is nullable. So I've use a 
UniqueConstraint like:

class Item(Model):
    name = models.CharField(max_length=200, null=False)
    unit = models.CharField(max_length=20, null=True)
    owner = models.CharField(max_length=200, null=True)
    class Meta:
        constraints = [
          models.UniqueConstraint(
              name='%(app_label)s_%(class)s_name_unit_owner_uniq',
              fields=('name', 'unit', 'owner')
          ),
        ]

Unfortunately I wasn't achieving what I wanted. In that simple example a 
user could create duplicated records for unit = None. Also, It is possible 
to create duplicated records where .This behavior conforms the SQL 
standards, of course. 
In this article 
<https://wladimirguerra.medium.com/only-one-null-in-unique-columns-234672fefc08>
 I 
explain how I have done to get the wanted behavior and the reasons that it 
might be cumbersome in some cases. In the same article I show an SQL 
expression that is clean and should result in a way more DRY code in model 
declaration. The SQL expression is:

CREATE UNIQUE INDEX core_item_name_unit_owner_uniq
     ON public.core_item (name, COALESCE(owner,"-"), COALESCE(unit,"-"));

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/161489b2-b752-450f-a3d4-6fcecd51afccn%40googlegroups.com.

Reply via email to