Class import error in django
I have a django app called client. Inside customer.models
I have some model classes, one of which is Tooth. I also created a new python file inside my app directory called callbacks.py to keep some callback functions for some signlas. I am doing 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 import error
from customer.models import Tooth
ImportError: cannot import name Tooth
Everything else all other products are working fine.
EDIT: Using Django 1.6 version
source to share
This is a circular import.
Here's what's going on:
- Django loads models
- Therefore django will import
customer.models
- Python executes content
customer/models.py
to compute module attributes -
customers/models.py
importcustomer/callbacks.py
- Python canceled execution
customer/models.py
and starts executioncustomer/callbacks.py
-
callbacks.py
try importingmodels.py
which is imported. Python prevents double imports of the module and raises the ImportError.
Usually this situation shows bad design. But sometimes (it seems to be your case) a hard link is required. One quick and dirty way to fix this is to defer cyclic imports 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
source to share