在Django中,您可以为模型创建管理器。为此managers.py
,我在模型中添加了一个名为和的新文件objects = MyManager()
。
要停止循环进口,我愿意self.model
。但是,如果我需要在经理中引用其他模型,即
from models import SecondModel
second= SecondModel(name=test).save()
self.model(second=second)
我收到以下错误: ImportError: cannot import name SecondModel
那么Django中有没有一种方法可以延迟加载模型?
您有几种选择:
Django具有用于按字符串名称导入的实用程序功能,因此您无需自行导入。有几种可用的方法(请参阅此问题:Django:从字符串获取模型?)
from django.db.models.loading import get_model
class SomeModelManager(...):
...
def some_function(self):
model = get_model('your_app', 'YourModel')
object = model()
在managers.py
文件底部添加导入,并确保仅导入模块而不是模型本身。
所以...
models.py
:
import managers
class SomeModel(models.Model):
...
objects = managers.SomeModelManager()
managers.py
class SomeModelManager(...):
...
def some_function(self):
object = models.SomeOtherModel()
import models
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句