Django Makemigrations not working with ForeignKey field to an app that has AppConfig

Viewed 71

We have an app called sessions, and since Django has similar django.contrib.sessions app, we need to create an AppConfig to fix the "duplicate app" error, that is, we set the app label as common.sessions.

So, we have this folder/files structure:

common
    sessions
        __init__.py
        apps.py
        models.py

__init__.py

default_app_config = 'common.sessions.apps.CommonSessionsConfig'

apps.py

class CommonSessionsConfig(AppConfig):
    name = 'common.sessions'
    label = 'common.sessions'

models.py

class SessionEventType(models.Model):
    name = models.CharField()

class SessionEventTypeMapping(models.Model):
    session_event_type = models.ForeignKey(SessionEventType)

settings.py

INSTALLED_APPS = (
    'common.sessions',
    ...
)

Running manage.py migrations will throw this error:

  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle
    migration_name=self.migration_name,
  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes
    changes = self._detect_changes(convert_apps, graph)
  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 111, in _detect_changes
    self.new_apps = self.to_state.apps
  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 166, in apps
    return StateApps(self.real_apps, self.models)
  File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 248, in __init__
    raise ValueError(msg.format(field=operations[0][1], model=lookup_model))
ValueError: Lookup failed for model referenced by field common.sessions.SessionEventTypeMapping.session_event_type: common.sessions.common.sessions.SessionEventType

Apparently, it fails on this part and could not locate the SessionEventType class/model even though they're just in the same models.py file, and ended up looking for common.sessions.common.sessions.SessionEventType which is strange:

session_event_type = models.ForeignKey(SessionEventType)

Tried also this variant:

session_event_type = models.ForeignKey('common.sessions.SessionEventType')

but it didn't help, as well as this related issue. By the way, we're still using Py2/Django1.8 since it's a huge project and we couldn't upgrade the version easily. Are we missing something? Checked the AppConfig/ForeignKey docs but seems no related info for it. No thrown error also if we don't use an FK field (i.e. non-relation field migrations are ok). We just want the makemigrations to work.

0 Answers
Related