其他模型中的导入模型方法

发布于 2025-01-31 20:22:50 字数 541 浏览 2 评论 0原文

我正在为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不念旧人 2025-02-07 20:22:50

您可以使用get_model函数,该功能是为懒惰模型导入的。

from django.apps import apps
YourModel = apps.get_model('your_app_name', 'YourModel')

You can use the get_model function which is designed for lazy model imports.

from django.apps import apps
YourModel = apps.get_model('your_app_name', 'YourModel')
痴情 2025-02-07 20:22:50

您可以使用get_model并在调用该函数时导入其他模型:

from django.apps import apps

Class B:
    @classmethod
    def bar():
        A = apps.get_model('app_name', 'A')
        a = A()
        a.foo()

也可以以相反的方式进行。

You can use get_model and import the other model when the function is called:

from django.apps import apps

Class B:
    @classmethod
    def bar():
        A = apps.get_model('app_name', 'A')
        a = A()
        a.foo()

It's possible to do it the other way around also.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文