其他模型中的导入模型方法
我正在为API使用Django REST框架,在该框架中我需要将一种从一个模型中使用到另一种模型的方法。但是,这导致
Importerror:无法从部分初始化的模块'...'导入名称'...'(最有可能归因于循环导入)
我的模型样本如下:
a
from ..B.models import B
Class A:
@classmethod
def foo():
b = B()
b.bar()
模型B
from ..A.models import A
Class B:
@classmethod
def bar():
a = A()
a.foo()
我知道由于 ciruclar导入而导致的错误。 有什么方法可以在彼此的模型中导入方法?
I'm using Django Rest Framework for API where I need to use methods from one model into another. But, this results in
ImportError: cannot import name '...' from partially initialized module '...' (most likely due to circular import)
My models samples are as follows:
Model A
from ..B.models import B
Class A:
@classmethod
def foo():
b = B()
b.bar()
Model B
from ..A.models import A
Class B:
@classmethod
def bar():
a = A()
a.foo()
I understand the error is being caused to due to ciruclar import.
Is there any way to import methods in each other's model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
get_model
函数,该功能是为懒惰模型导入的。You can use the
get_model
function which is designed for lazy model imports.您可以使用
get_model
并在调用该函数时导入其他模型:也可以以相反的方式进行。
You can use
get_model
and import the other model when the function is called:It's possible to do it the other way around also.