Django circular model reference

前端 未结 8 1318
长发绾君心
长发绾君心 2020-11-29 07:42

I\'m starting to work on a small soccer league management website (mostly for learning purposes) and can\'t wrap my mind around a Django models relationship. For simplicity,

相关标签:
8条回答
  • 2020-11-29 08:23

    as you can see in the docs, for exactly this reason it is possible to specify the foreign model as a string.

    team = models.ForeignKey('Team')
    
    0 讨论(0)
  • 2020-11-29 08:24

    Here is another way to tackle this problem. Instead of creating a circular dependency, I created an additional table that stores the relationship between players and teams. So in the end it looks like this:

    class Team(Model):
        name = CharField(max_length=50)
    
        def get_captain(self):
            return PlayerRole.objects.get(team=self).player
    
    class Player(Model):
        first_name = CharField(max_length=50)
        last_name = CharField(max_length=50, blank=True)
    
        def get_team(self):
            return PlayerRole.objects.get(player=self).team
    
    PLAYER_ROLES = (
        ("Regular", "Regular"),
        ("Captain", "Captain")
        )
    
    class PlayerRole(Model):
        player = OneToOneField(Player, primary_key=True)
        team = ForeignKey(Team, null=True)
        role = CharField(max_length=20, choices=PLAYER_ROLES, default=PLAYER_ROLES[0][0])
        class Meta:
            unique_together = ("player", "team")
    

    It might be slightly less efficient in terms of storage than the suggested workaround, but it avoids the circular dependency and keeps the DB structure clean and clear. Comments are welcome.

    0 讨论(0)
提交回复
热议问题