我可以在django中将模型分成不同的文件 [英] Can i divide the models in different files in django

查看:85
本文介绍了我可以在django中将模型分成不同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我所有的模型都在m​​odels.py中。我会很杂乱。
我可以使用单独的文件,如 base_models.py ,以便将我的主要模型放在那里,我不想触摸



同样的情况,视图和放在单独的文件夹,而不是开发一个新的应用程序

解决方案

是,它是可行的。这不是特别漂亮:



使模型成为一个模块,因此您的目录结构如下所示:

   - 模型
| - __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'


Currently all my models are in models.py. Ist becomming very messy. Can i have the separate file like base_models.py so that i put my main models there which i don't want to touch

Also same case for views and put in separate folder rather than develop a new app

解决方案

Yes, it's doable. It's not particularly pretty though:

make models a module, so your directory structure looks like this:

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

now, the magic lies in __init__.py and some little extras in the models. __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'

这篇关于我可以在django中将模型分成不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆