[Answered ]-Django DM model constraint: uniqueConstraint or checkConstraint?

1👍

Since , you could make a functional unique constraint with the Least [Django-doc] and Greatest [Django-doc] of the two, so:

from django.db.models.functions import Least, Greatest


class ConnectionRequest(models.Model):
    senderAccount = models.ForeignKey(
        Account, related_name='sender_Account', on_delete=models.CASCADE
    )
    recipientAccount = models.ForeignKey(
        Account, related_name='recipient_Account', on_delete=models.CASCADE
    )
    requested = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.senderAccount_id}  to {self.recipientAccount_id}'

    class Meta:
        constraints = [
            models.UniqueConstraint(
                name='duplicate_connreq_constraint',
                fields=['senderAccount', 'recipientAccount'],
            ),
            models.CheckConstraint(
                name='self_connection_request_constraint',
                check=~models.Q(senderAccount=models.F("recipientAccount")),
            ),
            models.UniqueConstraint(
                Least('senderAccount', 'recipientAccount'),
                Greatest('senderAccount', 'recipientAccount'),
                name='antisymmetric',
            ),
        ]

Leave a comment