naglas
naglas

Reputation: 492

How to add constraint for 2 fields not having the same value?

How to write a check that checks if two objects of the same model are not the same object?

class Foo(models.Model):
    first = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='first')
    second = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='second')

    class Meta:
        constraints = [
            CheckConstraint(name='not_same', check=(first!=second))
        ]

Upvotes: 1

Views: 795

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You can use an F object [Django-doc] to refer to a field, so:

from django.db.models import F, Q

class Foo(models.Model):
    first = models.ForeignKey(
        Bar,
        on_delete=models.CASCADE,
        related_name='first'
    )
    second = models.ForeignKey(
        Bar,
        on_delete=models.CASCADE,
        related_name='second'
    )

    class Meta:
        constraints = [
            CheckConstraint(name='not_same', check=~Q(first=F('second')))
        ]

Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the Bar model to the Foo model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the first relation to foo_first.

Upvotes: 3

Related Questions