我有以下文件:
用户.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
公司.py
...
from models.user import User
class Company(BaseModel):
user = ForeignKeyField(User, ...)
...
就python而言,这是一个正常的循环导入错误。问题是通常的解决方法(将导入语句放在文件末尾,以不同的方式导入等)在这种情况下不起作用,因为我在类属性的定义中使用了一个类另一个类。
在这种情况下解决循环导入错误的正确方法是什么?
请您参考如下方法:
正如@PatrickHaugh 指出的那样,事实证明这实际上不可能:
Note that you can't define both of these in the same file as they are written. When you execute the first definition, it will fail because the name of the other class hasn't been defined yet, no matter which you define first. What framework is ForeignKeyField from? It may have tools for circumventing this.
因为我正在使用 peewee作为我的 ORM,有一个专门为此用途构建的字段:DeferredForeignKey。
所以,最终,解决方案是:
用户.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
公司.py
...
class Company(BaseModel):
user = DeferredForeignKey('User', ...)
...
