There is a model: models.py

class Country(models.Model): id = models.IntegerField(primary_key=True, unique=True) # Код страны name = models.CharField(max_length=100) # Название страны class Area(models.Model): id = models.IntegerField(primary_key=True, unique=True) # Код региона name = models.CharField(max_length=100) # Название региона country = models.ForeignKey(Country) # Код страны capital = models.ForeignKey(City) # Код столицы региона class City(models.Model): id = models.IntegerField(primary_key=True, unique=True) # Код города name = models.CharField(max_length=100) # Название города country = models.ForeignKey(Country) # Код страны area = models.ForeignKey(Area) # Код региона 

It is necessary in the Area (regions) to have a link to the city (administrative center) in the City .

Accordingly, I get the error in the traceback:

 NameError: name 'City' is not defined 

    1 answer 1

    At the time of initialization of the ForeignKey (City), the City model has not yet been created, so either transfer it above the creation of the Area model, or type the model name inline:

     capital = models.ForeignKey('City', related_name='capitals') # Код страны 
    • City above can not be transferred, because there are links to Country and Area. If you do this: capital = models.ForeignKey ('City'), then I get the traceback: one or more models: Reverse query name Add a definition for the 'capital'. - Kanvi
    • one
      Well, that's another problem. Read your traceback carefully, everything is written there. Corrected the code in the answer, try. - MyNameIss
    • Thanks, I read in the docks that such_name. Corrected. It works now. Appeared the task of filtering cities when choosing the admin center, but this is not a problem - Kanvi