Django Models

UniqueConstraint

Adapted from How to have unique=True email addresses while allowing for null=true

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

class Contact(TimedCreateModifyDeleteModel):
    # ...
    msgraph_user_uuid = models.UUIDField(null=True)

    class Meta:
        # ...
        # If we have a ``msgraph_user_uuid``, then it must be unique.
        constraints = [
            models.UniqueConstraint(
                "msgraph_user_uuid",
                name="constraint_unique_msgraph_user_uuid_no_null",
                condition=Q(msgraph_user_uuid__isnull=False),
            )
        ]