Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.modelsclassQuiz(models.Model):
    lesson = models.ForeignKey(
        'courses.Lesson',
        on_delete=models.DO_NOTHING
    )
    # …

Post a Comment for "Django Models How To Fix Circular Import Error?"