Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error importing class in django

Tags:

python

django

I have a django app called customer. Inside customer.models I have some model classes one of them is Tooth. I also created a new python file inside my app's directory called callbacks.py to store some callback functions for some signlas. What I do is the following

from customer.models import Tooth

def callback(sender, **kwargs)
    #using Tooth here

and on models.py

from customer.callbacks import callback
#.....
post_save.connect(callback, sender=Customer)

But when I try to run sqlall I get an import error

    from customer.models import Tooth
ImportError: cannot import name Tooth

Everything else all other imports work normally.

EDIT: Using Django 1.6 version

like image 739
Apostolos Avatar asked May 31 '26 10:05

Apostolos


1 Answers

This is a circular import.

Here's what happens:

  • Django loads up the models
  • Therefore, django imports customer.models
  • Python execute the content of customer/models.py to compute the attributes of the module
  • customers/models.py imports customer/callbacks.py
  • Python set aside the execution of customer/models.py and starts executing customer/callbacks.py
  • callbacks.py try to import models.py which is being imported. Python prevents double importation of the module and raises an ImportError.

Usually these kind of situation show a poor design. But sometimes (which seems to be your case) tight coupling is required. One quick and dirty way to fix this is to delay the circular import, in your case:

In models.py:

from customer.callbacks import callback

# Define Tooth

post_save.connect(callback, sender=Customer)

In callbacks.py:

def callback(sender, **kwargs)
    from customer.models import Tooth
    # Use Tooth
like image 119
Antoine Catton Avatar answered Jun 02 '26 22:06

Antoine Catton