Python Django中模型和助手之间的循环导入
我试图在我的Django应用程序中添加一个Python Django中模型和助手之间的循环导入,python,django,python-2.7,signals,Python,Django,Python 2.7,Signals,我试图在我的Django应用程序中添加一个post_save信号,遇到了一个循环导入问题 helpers.py from tracker.models import Record def get_account_id(name): return name + '123' from helpers import get_account_id class Record(models.Model): id = models.AutoField(primary_key=True
post_save
信号,遇到了一个循环导入问题
helpers.py
from tracker.models import Record
def get_account_id(name):
return name + '123'
from helpers import get_account_id
class Record(models.Model):
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=120, blank=True)
matched_account_id = models.CharField(max_length=120, unique=False, blank=True)
def find_matched_account(sender, instance, *args, **kwargs):
instance.matched_account_id = get_account_id(instance.name)
instance.save()
pre_save.connect(find_matched_account, sender=Record)
models.py
from tracker.models import Record
def get_account_id(name):
return name + '123'
from helpers import get_account_id
class Record(models.Model):
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=120, blank=True)
matched_account_id = models.CharField(max_length=120, unique=False, blank=True)
def find_matched_account(sender, instance, *args, **kwargs):
instance.matched_account_id = get_account_id(instance.name)
instance.save()
pre_save.connect(find_matched_account, sender=Record)
这显然是一种简化,但总结了我遇到的问题。我可以将
helpers
中的代码移动到models
中,但更愿意将类似的内容存储在helpers
中,因为我最终会在其他地方使用它。将导入移动到函数中
编辑:提交这个有点过早:p
当您的导入位于文件顶部时,将在导入该文件后立即执行导入。这会导致此类错误
您可以将导入限制在函数的作用域内,以避免此问题
当您遇到这个问题时,您至少应该再次检查您的体系结构是否真正合适。它有时(但肯定不总是)表明您的体系结构可以改进
我发现,您通常可以将函数从模型移动到帮助程序,并将函数的第一个参数作为模型的实例。这样,您就可以让一个助手导入一个助手
(第二次编辑:删除了示例代码,这毫无意义)挑战在于我可能会将
记录
导入到助手中的十几个函数中。这是一个问题还是其中一个问题?@kmomo为我最初的简短回答道歉。我不是故意这么快就屈服的。我用一个例子更新了答案。一般来说,这个问题可以通过重组来解决。不过,偶尔,您只需要移动导入的范围。aa再看看,我误解了您的问题。不过,我建议将find\u matched\u账户
转移给助手。