Django circular model reference

前端 未结 8 1339
长发绾君心
长发绾君心 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:19

    Have a Captain table that has player/team columns along with your other tables, and make captain a method of Team:

    class Team(models.Model):
        name = models.CharField()
        def captain(self):
          [search Captain table]
          return thePlayer
    
    class Player(models.Model):
        name = models.CharField()
        team = models.ForeignKey(Team)
    
    class Captain(models.Model):
        player = models.ForeignKey(Player)
        team = models.ForeignKey(Team)
    

    You'd have to check that you never have more than one captain in the same team though... But you don't have any circular references that way. You could also end up with a captain who isn't in the team he's flagged as captain of. So there's a few gotchas this way.

提交回复
热议问题