Django外键分配问题

时间:2019-04-07 21:27:35

标签: python django

我有一系列相关模型。国家->联赛->球队->球员。该模型可以很好地将国家/地区与联赛以及联赛与球队联系起来,但是随着球队参加多个比赛,球队的ID也有所不同。为了解决这个问题,我为每个团队添加了一个带有ID的引用列。我想将此ref列用作播放器模型中的外键,但是当我尝试将数据解析到Postgres数据库时遇到错误。

我尝试使用to_field和unique = True,但仍然会出现错误。我环顾四周,但尚未找到解决方案。

这是我的模特代码:

from django.conf import settings
from django.db import models
from django.utils import timezone
import datetime


class Country(models.Model):
    objects = models.Manager()
    name = models.CharField(max_length=50,default="TBA")
    id = models.IntegerField(primary_key=True,default=0)


    def __str__(self):
        return self.name

    def __unicode__(self):
        return u'%s' % self.name

class League(models.Model):
    objects = models.Manager()
    name = models.CharField(max_length=100,default="TBA")
    id = models.IntegerField(primary_key=True,default=0)
    country = models.ForeignKey(Country,on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return u'%s' % self.name


class Team(models.Model):
    objects = models.Manager()
    name = models.CharField(max_length=100,default="TBA")
    id = models.IntegerField(primary_key=True,default=0)          
    league = models.ForeignKey(League,on_delete=models.CASCADE)
    ref = models.IntegerField(default=0)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return u'%s' % self.name

class Player(models.Model):
    objects = models.Manager()
    name = models.CharField(max_length=64)
    id = models.IntegerField(primary_key=True)
    first_name = models.CharField(max_length=64,default="Unknown")
    last_name = models.CharField(max_length=64,default="Unknown")
    nationality = models.CharField(max_length=64,default="Unknown")
    date_of_birth = models.DateField(default = datetime.date.today)
    position = models.CharField(max_length=64, default="Unknown")
    team_ref =models.ForeignKey(Team,to_field="ref",on_delete=models.CASCADE)

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:0)

恕我直言,我认为您的模型设计有点错误。您应将“团队与联盟”关系设置为ManyToMany字段。这样,一个团队可以分配给多个联赛。如果要为不同的锦标赛维护不同的小队,则应创建一个名为Squads的新模型并将其用作through,并与Player中的该小队模型建立多对多关系。例如:

class Team(models.Model):
   # other fields

   league = models.ManyToManyField(League, through="Squad")

class Squad(models.Model):
   team = models.ForeignKey(Team)
   league = models.ForeignKey(League)


class Player(models.Model):
   squad = models.ManyToManyField(Squad)