我想从模型的保存方法中触发视图函数,以便写入或更新与实例关联的 xml 文件。
#models.py
from myapp.views import updateXML, createXML
class myModel(models.Model):
def save(self, *args, **kwargs):
if self.pk is not None:
updateXML(self)
else:
createXML(self)
super(FatherAgendaTemplate, self).save(*args, **kwargs)
#views.py
from myapp.models import otherModel
def createXML(instance):
print "create XML"
print instance
def updateXML(instance):
print "update XML"
print instance
问题是我需要将 otherModel 导入到具有 myModel 外键的 views.py 中,这会导致某种冲突,并且出现错误:
ImportError: cannot import name createXML
我想我的做法是错误的,像这样在模型和视图之间导入,因为它会引发导入错误。这样做的正确方法是什么?当然,我可以在 models.py 中完成所有的 xml 编写功能并避免导入冲突,但这似乎是一种混乱的方法。