Reputation: 492
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
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 theBar
model to theFoo
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 therelation tofirst
foo_first
.
Upvotes: 3