2012-12-05 58 views
8

目前我所有的模型都在m​​odels.py中。我很害怕。 我能有一個像base_models.py單獨的文件,以便我把我的主要機型有,我不想碰我可以在django的不同文件中分割模型嗎

也爲同樣的觀點和案例放在單獨的文件夾,而不是開發新的應用程序

回答

10

是,這是可行的。這不是特別漂亮,但:

讓模特模塊,讓你的目錄結構是這樣的:

- models 
|- __init__.py 
|- some_model.py 
|- some_other_model.py 
|- ... 

目前,神奇之處在於__init__.py和模型的一些小演員。 __init__.py

from some_model import SomeModel 
from some_other_model import SomeOtherModel 

__all__ = [ 
    'SomeModel', 
    'SomeOtherModel', 
] 

some_model.py:

class SomeModel(models.Model): 
    class Meta(object): 
     app_label = 'yourapplabel' 
     db_table = 'yourapplabel_somemodel' 
+0

感謝下劃線acjohnson55,早上有點早 – tback

0

是的,只是做了一個名爲models文件夾,該文件夾把所有的分離模型文件英寸你需要把一個名爲__init__.py文件中的文件夾models它被認爲是models模塊。在__init__.py,使用from ... import ...把你想獲得直接yourapp.models的名字,否則,你將不得不進口其作爲yourapp.models.base_model,或無論您使用的子模塊的名稱。

此外,在每一個模型,你必須添加一個名爲app_label = 'yourapp',以確保您的模型被認爲是應用程序的一部分元屬性。

0

您可以將模型文件中分離這樣的:
-------型號/
--------- ----- init .py
-------------- usermodels.py
--------------othermodel.py

初始化的.py


--------------- from usermodels import *
--------------- from othermodel import *
and * in * models。 PY,加入META類:
--------類元:
-------------- app_label = 'APPNAME'

相關問題