DevOps/TIL

[ERROR] most likely due to a circular import

bestwish 2023. 6. 12. 12:26

문제발생

제목에 있는 에러는 순환참조 에러로, 두 개 이상의 모듈이 서로를 참조하고 있는 상태이다.

이 에러가 발생하게 된 이유는 서로 다른 app의 models.py에서 import를 참조했기 때문이다.

# user/models.py
from product.models import Brand

class Coupon(models.Model):
	...
    
    
class CouponUser(models.Model):
	...

# product/models.py
from coupons.models import CouponUser


class AlProduct(models.Model):
	...
    
    
class AlProductImage(models.Model):
	...


class AlProductOption(models.Model):
	...


class Order(models.Model):
	...


class OrderDetail(models.Model):
   	...


class OrderStatus(models.Model):
	...

 

해결방법

  1. 모듈 재구성: 모듈 간의 의존성을 조정하여 순환 참조를 제거합니다. 모듈을 재구성하여 각 모듈이 필요로 하는 최소한의 의존성만 가지도록 설계합니다.
  2. 필요한 위치에서 import: 모듈 간의 의존성을 최소화하기 위해, 필요한 모듈을 사용하는 시점에서 import를 수행합니다. 예를 들어, 함수나 메서드 내에서 필요한 모듈을 import하는 방식을 고려할 수 있습니다.
  3. 느슨한 결합(Loose Coupling) 적용: 인터페이스나 추상화를 사용하여 모듈 간의 결합도를 낮춥니다. 이를 통해 의존성이 감소하고 순환 참조를 방지할 수 있습니다.
  4. 중간 모듈 도입: 모듈 간의 의존성을 해결하기 위해 중간 모듈을 도입할 수 있습니다. 중간 모듈은 다른 모듈들의 의존성을 관리하고 조정하는 역할을 수행하여 순환 참조를 방지합니다.

나는 1번의 방법을 이용하여 수정을 완료하였다.

해결

# user/models.py
from product.models import Brand

class Coupon(models.Model):
	...
    
    
class CouponUser(models.Model):
	...

# product/models.py
from coupons.models import CouponUser


class AlProduct(models.Model):
	...
    
    
class AlProductImage(models.Model):
	...


class AlProductOption(models.Model):
	...


# order/models.py
class Order(models.Model):
	...


class OrderDetail(models.Model):
   	...


class OrderStatus(models.Model):
	...

나는 Product 관련된 것과 Order 관련된 것을 좀 더 세밀하게 나누었다.

(Order에서 User가 사용되고, Product에서는 사용되지 않았다.)