0
class Team(models.Model):
    team_name = models.CharField(max_length=50, null=False)

    def __str__(self):
        return self.team_name


class Tournament(models.Model):
    types = (
        ('Round', 'Round'),
        ('Knockout', 'Knockout'),
    )
    teams = models.ManyToManyField(Team, related_name='tournament_teams')
    tournament_name = models.CharField(max_length=50, null=False)
    tournament_type = models.CharField(choices=types, max_length=40, null=False)

    def __str__(self):
        return self.tournament_name


class MatchRound(models.Model):
    team_a_id = models.ForeignKey(Team, related_name="team_a")
    team_b_id = models.ForeignKey(Team)
    date = models.DateTimeField(null=True)
    team_a_score = models.IntegerField(null=True)
    team_b_score = models.IntegerField(null=True)
    tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True)

    @receiver(post_save, sender=Tournament)
    def create_match_round(sender, **kwargs):
        type = kwargs.get('instance').tournament_type
        if type == 'Round' and kwargs.get('created', False):
            teams = kwargs.get('instance').teams.all()
            schedule = create_schedule(teams)
            for round in schedule:
                for match in round:
                    team_a_id = match[0]
                    team_b_id = match[1]
                    tournament_id = kwargs.get('instance')
                    game = MatchRound.objects.create(team_a_id=team_a_id, team_b_id=team_b_id,
                                                     tournament_id=tournament_id)

I am trying to create a schedule for a tournament. So, I set up a trigger on MatchRound model and I am trying to get the teams of the tournament when it's created. However, the following line

teams = kwargs.get('instance').teams.all()

returns to an empty query set. I couldn't figure it out the problem.

cnian
  • 239
  • 4
  • 18
  • That's because there are no related models yet when Tournament is saved, because they cannot be linked to the Tournament. You're looking for the [m2m_changed](https://docs.djangoproject.com/en/1.11/ref/signals/#django.db.models.signals.m2m_changed) signal. –  Jun 22 '17 at 15:17
  • @Melvyn that is logical. So, Should I set up m2m_changed signal under Tournament or MatchRound model? – cnian Jun 22 '17 at 15:21
  • "Whatever makes most sense to you". The signal gets passed all the information to figure out what change you're dealing with and in what stage of the change you are. Put it where it still makes sense when you read it back in 3 months. –  Jun 22 '17 at 15:25

0 Answers0