Search code examples
pythondjangodjango-modelspython-importimporterror

Django models how to fix circular import error?


I read about a solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure.

Directory structure

quiz/models.py

import apps.courses.models as courses_models


class Quiz(models.Model):
    lesson = models.ForeignKey(courses_models.Lesson, on_delete=models.DO_NOTHING)  # COURSE APP MODEL IMPORTED

courses/models.py

import apps.quiz.models as quiz_models


class Lesson(models.Model):
   ...

class UserCompletedMaterial(models.Model):
   ...
   lesson = models.ForeignKey(Lesson)
   quiz = models.ForeignKey(quiz_models.Quiz)  # QUIZ APP MODEL IMPORTED


How you can see I just can't keep it together or something else..
Because I think the UserCompletedMaterial model is a part of courses app


Solution

  • Both models refer to each other, and this thus means that in order to interpret the former, we need the latter and vice versa.

    Django however has a solution to this: you can not only pass a reference to the class as target model for a ForeignKey (or another relation like a OneToOneField or a ManyToManyField), but also through a string.

    In case the model is in the same application, you can use a string 'ModelName', in case the model is defined in another installed app, you can work with 'app_name.ModelName'. In this case, we thus can remove the circular import with:

    # do not import the `courses.models
    
    class Quiz(models.Model):
        lesson = models.ForeignKey(
            'courses.Lesson',
            on_delete=models.DO_NOTHING
        )
        # …