我如何在django中分离我的模型? [英] How do I separate my models out in django?
问题描述
我正在尝试学习python / django。
现在,我在models.py中有我所有的模型
是否可以让我的模型分解,以便我可以在单独的模型文件夹中单个文件,以便我可以执行以下操作:
〜/ myproject / myapp / models / user.py
〜/ myproject / myapp / models / group.py
谢谢
可以确保导入您创建的所有模型 __ init __。py
您的型号
目录。在你的情况下,它将如下所示:
#__init__.py
来自用户导入UserModel
从组导入GroupModel
这需要做,因为Django查找应用程序。
正如其他人所说,对于1.7之前的Django版本,您还需要指定您的应用程序的您的型号中 Meta
类中的 app_label
属性中的名称:
$ b $
$ b $ Meta
app_label =myapp
http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label
I'm trying to learn python/django.
Right now, I have all of my models in models.py
Is it possible to have my models broken out so that I can have a single file per model in a separate models folder so that I can do something like:
~/myproject/myapp/models/user.py ~/myproject/myapp/models/group.py
Thanks
It is possible, just make sure to import all the models you create in __init__.py
in your models
directory. In your case, it would look like this:
# __init__.py
from user import UserModel
from group import GroupModel
This needs to be done because Django looks in app.models
for an app's models.
As others have mentioned, for versions of Django prior to 1.7, you'll also need to specify your app's name in the app_label
attribute in the Meta
class in your model:
class UserModel(models.model):
# fields here
class Meta:
app_label = "myapp"
http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label
这篇关于我如何在django中分离我的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!