如何在Django中创建模型包 [英] How to create a package of models in Django
问题描述
我有一个很大的 models.py
文件(包含多个模型),我正在尝试重构,每个文件一个模型.
Having a quite large models.py
file (which contains several models), I'm trying to refactor, with one model per file.
因此,我正在尝试创建具有以下结构的 models
包:
I'm therefore trying to create a models
package, with the following structure:
-
app/models/__ init __.py
-
app/models/first_model.py
-
app/models/second_model.py
不幸的是,我无法使Django惰性参考机制正常工作,即:
Unfortunately, I cannot get Django lazy reference mechanism to work well, i.e.:
first_model = models.ForeignKey('app.FirstModel')
返回Django无法找到模型的错误.
returns the error that Django cannot find the model.
有什么主意吗?谢谢!
推荐答案
它应该起作用,请确保在__init__.py中从first_model.py和second_model.py导入所有模型.
It should work, make sure that in __init__.py you are importing all the models from first_model.py and second_model.py.
from .first_model import FirstModel
from .second_model import SecondModel
如果要以'app_label.model_name'检索模型,则必须将它们导入__init__.py,否则可以尝试以下操作:
If you want to retrieve the models as 'app_label.model_name', then you will have to import them in __init__.py, otherwise you can try the following:
使用 https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.apps.get_model
或者您可以使用ContentTypes:https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#methods-on-contenttype-instances
Or you can use ContentTypes: https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#methods-on-contenttype-instances
这篇关于如何在Django中创建模型包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!