Django circular model reference

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

    Although there is nothing wrong with having two references to the same model, perhaps there is a better way to solve this particular problem.

    Add a boolean to the Team model to identify a player + team combination as captain:

    class Team(models.Model):
      player = models.ForeignKey(Player)
      name = models.CharField(max_length=50)
      is_captain = models.BooleanField(default=False)
    

    To search for a team's captain:

    Team.objects.filter(is_captain=True)

    Personally I don't like this method because the search semantics don't make sense (ie, a "team" is not a "captain").

    The other approach is to identify each player's position:

    class Player(models.Model):
       name = models.CharField(max_length=50)
       position = models.IntegerField(choices=((1,'Captain'),(2,'Goal Keeper'))
       jersey = models.IntegerField()
    
       def is_captain(self):
         return self.position == 1
    
    class Team(models.Model):
       name = models.CharField(max_length=50)
       player = models.ForeignKey(Player)
    
       def get_captain(self):
          return self.player if self.player.position == 1 else None
    

    This makes a bit more sense when you search:

    Player.objects.filter(position=1) (return all captains)

    Team.objects.get(pk=1).get_captain() (return the captain for this team)

    In either case, however you have to do some pre save checks to make sure there is only one player for a particular position.

提交回复
热议问题