[Answered ]-How to prevent two ForeignKey entries in a model from being the same for each record in Django

1👍

You can add a CheckConstraint [Django-doc] such that the database will enforce this:

from django.db.models import F, Q


class Match(models.Model):
    team_a = models.ForeignKey(
        Team, related_name='matches_as_a', on_delete=models.CASCADE
    )
    team_b = models.ForeignKey(
        Team, related_name='matches_as_b', on_delete=models.CASCADE
    )
    match_date_time = models.DateTimeField(validators=[validate_matchdate])
    winner = models.CharField(
        choices=CHOICES, max_length=50, blank=True, null=True
    )

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=~Q(team_a=F('team_b')), name='not_play_against_itself'
            )
        ]

Leave a comment