'Conditional unique_together in Django

I have following unique constraint in my model.

class Meta:
        unique_together = (('crop', 'order', 'sku'),)

But sku may be null in some cases and in that case this unique_together is not working as null is not equal to null.i am thinking to make a conditional unique_together like if sku is not null then (('crop', 'order', 'sku'),) else (('crop', 'order'),).



Solution 1:[1]

Since , you can make use of Django's constraint framework, and add conditions to the UniqueConstraint [Django-doc]:

from django.db import models
from django.db.models import Q

class MyModel(models.Model):
    # …

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['crop', 'order', 'sku'],
                name='unique_1'
            ),
            models.UniqueConstraint(
                fields=['crop', 'order'],
                condition=Q(sku=None),
                name='unique_2'
            )
        ]

Note that not every database per se supports this and thus will enforce this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1