在 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 1.7 开始,当前接受的答案已被弃用;从这个答案 https://stackoverflow.com/questions/4881607/django-get-model-from-string/26126935#26126935,您可以像这样调整您的代码。
from django.apps import apps
class SomeModelManager(...):
...
def some_function(self):
model = apps.get_model(app_label='your_app', model_name='YourModel')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)