避免在 Django 中循环导入

avoid Circular import in Django

我有两个模型 Company 和 Actions:

from companies.models import Company

class Action(models.Model):

    company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE)

然后我在 utils.py

中有一个实用程序
from .models import Action

def create_action(user, verb, target_name=None, target=None):
    action = Action(user=user, verb=verb, target=target)

我在 def save 的公司模型中调用了这个实用程序,所以在公司模型中我有:

from not.utils import create_action 

so Action Model import Company Model as FK,utils import Action Model,Company Model import utils

现在,由于循环导入 Django 报错:

ImportError: cannot import name 'Company'

我在这里看到一些q/a直接使用import(没有from)我试过了但是没有用

import not.utils as nt
nt.create_action(...)

actions/models.pyuse a string 中删除 Company 导入:

class Action(models.Model):
    company = models.ForeignKey('companies.Company', blank=True, null=True, related_name='activity', on_delete=models.CASCADE)