Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading