0

我创建了一个带有几个类和外键的模型,并且能够将其保存在数据库中。

我有以下型号:

class Player_Bios(models.Model):
  my_id            = models.SlugField(unique=True)
  player_id        = models.IntegerField(max_length=50, unique=True)    
  name             = models.CharField(max_length=50) 
  last             = models.CharField(max_length=50)
  middle           = models.CharField(max_length=50, blank=True)

class BatStat (models.Model):
  player_id           = models.ForeignKey('Player_Bios')
  team_id             = models.ForeignKey('Team')
  bat_stat_id         = models.CharField(max_length=50, unique=True)
  sport_code           = models.CharField(max_length=50, blank=True) 
  ab                  = models.IntegerField(max_length=50, null=True)

class Team (models.Model):

  team_id             = models.IntegerField(max_length=50, unique=True)
  team_short          = models.CharField(max_length=50, blank=True)
  team_full           = models.CharField(max_length=50, blank=True)

当我将它保存到数据库时,我可以看到 Team 表上的 team_id 与 BatStat 表上的 team_id 相同,但 BatStat 上的 player_id 与 Player_Bios 表上的 player_id 不同。这是我将数据保存到数据库的方式:

p_id = Player_Bios.objects.get(player_id=st['player_id'])
t_id = Team.objects.get(team_id=st['team_id']) #I get the team_id from the Team Class
bat_id = str(st['season'])+ str(st['team_seq'])
bat_id = str(p_id.player_id) + bat_id
c = BatStat(player_id = p_id,team_id=t_id, bat_stat_id=bat_id, sport_code =st["sport_code"],ab=st['ab'])
c.save()

st['player_id'] 是一个字典。我做了一个打印,它显示了正确的 player_id 号码

4

1 回答 1

0

在 BatStat 中,您将密钥存储到 Player_Bios,而不是 player_id

class Player_Bios(models.Model):
  ...
  player_id        = models.IntegerField(max_length=50, unique=True)  

class BatStat (models.Model):
  ...
  player_id           = models.ForeignKey('Player_Bios')

我不确定为什么您的 team_id 相同,但是,您似乎已经有了 ID。您可以通过直接设置 id 来避免查找 Player_Bios 和 Team。

Django:使用整数设置外键?

class Player_Bios(models.Model):
  ...
  player_id = models.IntegerField(primary_key=True, max_length=50)  

class Team (models.Model):
  ...
  team_id = models.IntegerField(primary_key=True, max_length=50)

class BatStat (models.Model):
  ...
  player = models.ForeignKey('Player_Bios') # notice i renamed this to not have '_id'
  team = models.ForeignKey('Team') # notice i renamed this to not have '_id'

c = BatStat(bat_stat_id=bat_id, 
            sport_code =st["sport_code"],
            ab=st['ab'])
c.player_id = st['player_id'], # notice that this has '_id'
c.team_id = st['team_id'], # notice this has '_id'
c.save()
于 2013-01-30T03:45:26.370 回答