最近使用Python + Django,是一個巨複雜的系統,才幾天就40多張數據庫的表了。由於在Django裏面,表都使用類來實現的,因此就要一開始寫不少的class,語法都沒問題,可是有時候就會出現ImportError Can not import name xxxx
python
這個問題碰見了兩次,稍微有點差異,如今記錄一下來。數據庫
1.類之間的循環依賴
代碼大體是這樣的django
class Employee(models.Model): permission = models.ManyToManyField(Permission)
class Permission(models.Model): dealer = models.ForeiginKey(Dealer) name = models.CharField(max_length=20)
class Dealer(models.Model): employees = models.ManyToManyField(Employee)
這樣,Employee依賴Permission,Permission依賴Dealer,Dealer又會回到Employee,這樣確定就是錯誤的了。app
2.不一樣模塊之間的
Service.model 模塊.net
from Appointment.models import Appointment class Order(models.Model): appointment = models.ForeignKey(Appointment)
在Appointment.models裏面code
from Service.models import ServiceItem
這樣也會引用錯誤,這個緣由找了好長時間。
由於Order在引用Appointment的時候,會回到Service.models 查找Appointment引用的ServiceItem,可是這個時候Order的構建尚未完成,就會導入錯誤。這個和Python的機制有關係的。ci
3.解決辦法
今天又碰見這問題了,雖然找到了緣由,可是不知道怎麼去修改,由於畢竟業務邏輯在這,如今有stackoverflow上找到一個答案,真心好用。
也就是使用字符串表示模塊,而不進行導入了。
http://stackoverflow.com/questions/4379042/django-circular-model-import-help字符串
class Service(models.Model): appointment = models.ForeignKey("appointment.Appointment")
參考
http://www.douban.com/group/topic/43938606/
http://www.oschina.net/question/919901_88601
http://www.oschina.net/translate/top-10-mistakes-that-python-programmers-makeget