Home > Back-end >  how to use new table as a foreign key in existing table in django
how to use new table as a foreign key in existing table in django

Time:03-30

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

CodePudding user response:

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.

  • Related