Django中app的model相互引用问题

Django有俩个 app 

----------在 Course 的models.py中:

from Shopping.models import Coupon, OrderDetail

class Course:
  order_details = GenericRelation(to=OrderDetail)
  coupon = GenericRelation(to=Coupon)

-------------在Shopping的models.py中:

from Course.models import Account

class Coupon:
  account = models.ForeignKey(to=Account, verbose_name="拥有者", on_delete=None, related_name="coupons")

class OrderDetail:
  pass

报错:ImportError: cannot import name 'xxx'

原因:暂不清楚

解决方案:使用app_name.class_name的方式,注意不是app_name.models.class_name

在 Course 的models.py中:

class Course:
  order_details = GenericRelation(to="Shopping.OrderDetail")
  coupon = GenericRelation(to="Shopping.Coupon")

在Shopping的models.py中:

class Coupon:
  account = models.ForeignKey(to="Course.Account", verbose_name="拥有者", on_delete=None, related_name="coupons")

class OrderDetail:
  pass


原文地址:https://www.cnblogs.com/staff/p/12846765.html