Home > Blockchain >  Django - Can't import other app's model from same directory
Django - Can't import other app's model from same directory

Time:08-24

I've got a problem with importing model from another app for Foreign key. I tried two ways to use field from other model:

  1. Import it as a string, it doesn't provide any errors before migrating model:

    from_city = models.ForeignKey('cities.City', blank=True,
    null=True, related_name='from_city_set',
    on_delete=models.CASCADE)

It provides an error when i'm trying to use "makekigrations" or "migrate" command

  1. Import it as python object, but there is a strange moment. It tries to import 'city' app from src folder like that:

    from src.cities.models import City

    from_city = models.ForeignKey(City, blank=True, null=True, related_name='from_city_set', on_delete=models.CASCADE )

Both variants provides the same traceback:

Traceback (most recent call last):


File "C:\TrainProject\src\manage.py", line 22, in <module>
    main()
  File "C:\TrainProject\src\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 448, in execute
    output = self.handle(*args, **options)
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\TrainProject\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 196, in handle
    loader.project_state(),
  File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\loader.py", line 361, in project_state
    return self.graph.make_state(
  File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\graph.py", line 329, in make_state
    project_state = self.nodes[node].mutate_state(project_state, preserve=False)
  File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state
    operation.state_forwards(self.app_label, new_state)
  File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\operations\models.py", line 724, in state_forwards
    state.alter_model_options(
  File "C:\TrainProject\venv\lib\site-packages\django\db\migrations\state.py", line 182, in alter_model_options
    model_state = self.models[app_label, model_name]
KeyError: ('cities', 'city')

How can i solve it? 'train' app folder in the same place as 'cities' app.

UPD Installed apps:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cities',
'trains',]

Models (cities/models and trains/models):

class City(models.Model):
    name = models.CharField(max_length=40, unique=True, verbose_name='Название города')

class Train(models.Model):
name = models.CharField(max_length=50, unique=True,
                        verbose_name='Название поезда')
travel_time = models.PositiveSmallIntegerField(verbose_name='Время в пути')
from_city = models.ForeignKey('cities.City', related_name='from_city_set',
                              on_delete=models.CASCADE
                              )
to_city = models.ForeignKey('cities.City', related_name='to_city_set',
                            on_delete=models.CASCADE
                            )

CodePudding user response:

trains/models.py should be like this:

from src.cities import models as city_md

class Train(models.Model):
name = models.CharField(max_length=50, unique=True,
                        verbose_name='Название поезда')
travel_time = models.PositiveSmallIntegerField(verbose_name='Время в пути')
from_city = models.ForeignKey(city_md.City, related_name='from_city_set',
                              on_delete=models.CASCADE
                              )
to_city = models.ForeignKey(city_md.City, related_name='to_city_set',
                            on_delete=models.CASCADE
                            )

CodePudding user response:

Finally! I've solved this problem:

  1. Delete your DB file
  2. Delete everything from migrations folder in each app except file 'init.py'
  3. Run cmd 'python manage.py makemigrations' and 'python manage.py migrate'
  4. Problem solved!

UPD

It doesn't matter how you import another model to ForeingKey field, it can be a python string or a python object (of course after you imported this model):

from_city = models.ForeignKey('cities.City', related_name='from_city_set',
                              on_delete=models.CASCADE
                              )
_______________________________________________________________________

from city.models import City

from_city = models.ForeignKey(City, related_name='from_city_set',
                                  on_delete=models.CASCADE
                                  )
  • Related