本文介绍了如何在 Django 中分离我的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 python/django.

I'm trying to learn python/django.

现在,我的所有模型都在 models.py 中

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

谢谢

推荐答案

这是可能的,只要确保在 models 中导入你在 __init__.py 中创建的所有模型代码>目录.在您的情况下,它看起来像这样:

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

这需要完成,因为 Django 在 app.models 中查找应用程序的模型.

This needs to be done because Django looks in app.models for an app's models.

正如其他人提到的,对于 1.7 之前的 Django 版本,您还需要在 Meta 类中的 app_label 属性中指定应用程序的名称模型:

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 中分离我的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 08:59