[Answer]-Django modelling: Using the same data twice in the same object

1👍

Since you need to keep track of registrations and assign players into teams
I don’t see any other way
. Actually scratch that.

The existence of an intermediate(GamePlayerMembership) instance can signify whether
the player has registered or not for the game. So my take is this:

from django.db import models

class Player(models.Model):
    name = models.CharField()

class Game(models.Model):
    starts_when = models.DatetimeField()
    players = models.ManyToManyField(Player, through='GamePlayerMembership', related_name='games_played')

    def register(self, player):
        return GamePlayerMembership.objects.create(game=self, player=player)

    def assign(self, player, team):
        try:
            memb = GamePlayerMembership.objects.get(game=self, player=player)
            memb.team = team
            memb.save()
        except GamePlayerMembership.DoesNotExist:
            raise Exception('Player has not registered for the game')

class GamePlayerMembership(models.Model):
    TEAMS = (
        ('home', 'Home'),
        ('guest', 'Guest')
    )
    game = models.ForeignKey(Game)
    player = models.ForeignKey(Player)
    team = models.CharField(max_length=5, choices=TEAMS, null=True, blank=True)

    class Meta:
        unique_together = ('game', 'player')

Leave a comment