如何在 Django 中使用新 table 作为现有 table 的外键

how to use new table as a foreign key in existing table in django

大家好,我在 Dailytrip 中有两个模型 1,第二个是 Team,我需要在 Dailytrip 模型中使用 Team 模型作为外键,而 运行 Makemigrations 出现错误。我正在使用 django-2.2 和 python 3.7

Models.py

class DailyTrip(BaseModel):
    date = models.DateField(default=None)
    Team=models.ForeignKey(
        Team,
        models.CASCADE,
        verbose_name='Team',
        null=True,
        default=None
    )

class Team(BaseModel):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

错误

class DailyTrip(BaseModel):
  File "E:-march-2022\everest_jarvis\fleet\models.py", line 595, in DailyTrip
    Team,
NameError: name 'Team' is not defined

发生这种情况的原因是因为您在定义 Team 之前定义了 ForeignKey。可以先定义Team,所以:

class <strong>Team</strong>(BaseModel):
    # …
    pass

class DailyTrip(BaseModel):
    # …
    Team = models.ForeignKey(
        <strong>Team</strong>,
        models.CASCADE,
        verbose_name='Team',
        null=True,
        default=None
    )

或者如果这不可能,请使用字符串文字:

class DailyTrip(BaseModel):
    # …
    Team = models.ForeignKey(
        <strong>'Team'</strong>,
        models.CASCADE,
        verbose_name='Team',
        null=True,
        default=None
    )

class Team(BaseModel):
    # …

Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: team instead of Team.