如何在django中分离我的模型?

时间:2022-01-17 20:32:24

I'm trying to learn python/django.

我正在尝试学习python / django。

Right now, I have all of my models in models.py

现在,我将所有模型都放在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

〜/ myproject / myapp / models / user.py~ / myproject / myapp / models / group.py

Thanks

谢谢

2 个解决方案

#1


34  

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中创建的所有模型。在你的情况下,它看起来像这样:

# __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.

这需要完成,因为Django在app.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:

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

class UserModel(models.model):
    # fields here

    class Meta:
        app_label = "myapp"

http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label

http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label

#2


3  

you could have a folder called "models" but then in each model class you'll need to include:

你可以有一个名为“models”的文件夹,但是在每个模型类中你需要包括:

class Meta:
    app_label="appname goes here"

*ps. Don't forget a __ init__.py file like I always do.*

* PS。不要忘记像我一直这样的__ init__.py文件。*

#1


34  

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中创建的所有模型。在你的情况下,它看起来像这样:

# __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.

这需要完成,因为Django在app.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:

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

class UserModel(models.model):
    # fields here

    class Meta:
        app_label = "myapp"

http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label

http://docs.djangoproject.com/en/1.7/ref/models/options/#app-label

#2


3  

you could have a folder called "models" but then in each model class you'll need to include:

你可以有一个名为“models”的文件夹,但是在每个模型类中你需要包括:

class Meta:
    app_label="appname goes here"

*ps. Don't forget a __ init__.py file like I always do.*

* PS。不要忘记像我一直这样的__ init__.py文件。*