Home > Mobile >  Import model methods in other model
Import model methods in other model

Time:05-24

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?

CodePudding user response:

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')

CodePudding user response:

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.

  • Related