简体   繁体   中英

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

Hi Everyone i have two model 1 in Dailytrip and 2nd one is Team, i need to use Team model as foreign key in Dailytrip model, while run Makemigrations getting error. i am using django-2.2 and 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

Error

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

The reason this happens is because you define the ForeignKey before you define Team . You can define Team first, so:

class Team(BaseModel):
    # …
    pass

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

or if that is not possible, use a string literal:

class DailyTrip(BaseModel):
    # …
    Team = models.ForeignKey(
        'Team',
        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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM