How to apply different values ​​in multiple ForeignKey fields for Django

I have the following models in Django:

from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=200)


class Match(models.Model):                                                      
    team_home = models.ForeignKey(Team)                                                      
    team_visitors = models.ForeignKey(Team)                                                       
    league = models.CharField(max_length=200)                                                      
    date_played = models.DateField()  

The idea is to have a “Match” object, in which there are two teams that played a match in a game. It would be very strange for the team to play on their own. How can I guarantee that is team_homenot equal team_visitors?

+4
source share
2 answers

This cannot be done with pure Django. There is a ticket to add restrictions CHECK: https://code.djangoproject.com/ticket/11964

, team_home == team_visitors , , . , MySQL PostgresQL:

alter table myapp_match add constraint match_teams_not_equal check (team_home_id <> team_visitors_id);

. , , .

, team_home != team_visitors save:

class Match(models.Model):
    ....
    def save(self, *args, **kwargs):
        if self.team_home == self.team_visitors:
            raise Exception('attempted to create a match object where team_home == team_visitors')
        super(Match, self).save(*args, **kwargs)

- update queryset Django, Match , team_home == team_visitor.

+3

, unique_together Meta: unique_together

class Match(models.Model):
    ...
    class Meta:
        unique_together = ("team_home", "team_visitors")
0

Source: https://habr.com/ru/post/1626611/


All Articles