简体   繁体   English

对 Django 模型使用除 models.py 之外的其他文件名?

[英]Using other file names than models.py for Django models?

When creating a reusable app, should I put all models I define into single file models.py or can I group the models into several files like topic1.py , topic2.py ?创建可重用应用程序时,我应该将定义的所有模型放入单个文件models.py还是可以将模型分组到多个文件中,例如topic1.pytopic2.py

Please describe all reasons pro and contra.请描述赞成和反对的所有原因。

The models submodule is special in that it is automatically imported at a specific time during the initialization process. models子模块的特殊之处在于它在初始化过程中的特定时间自动导入。 All your models should be imported at this time as well.此时也应导入所有模型。 You can't import them earlier than that, and importing them later may cause errors.您不能在此之前导入它们,稍后导入它们可能会导致错误。

You can define your models in a different module, but you should always import all your models into your models.py or models/__init__.py .您可以在不同的模块中定义您的模型,但您应该始终将所有模型导入到models.pymodels/__init__.py Eg:例如:

# models/topic1.py

class Topic1(models.Model):
    ...

# models/__init__.py

from .topic1 import Topic1

If you import each model into models.py or models/__init__.py , that also allows you to import all the models directly from that file.如果您将每个模型导入到models.pymodels/__init__.py ,这也允许您直接从该文件导入所有模型。 In the example, that means that you can import Topic1 from myapp.models , not just from myapp.models.topic1 .在示例中,这意味着您可以从myapp.models导入Topic1 ,而不仅仅是从myapp.models.topic1 This way you can keep your models organized across multiple files without having to remember each model's precise location whenever you need to import them.通过这种方式,您可以在多个文件中组织模型,而无需在需要导入模型时记住每个模型的精确位置。

it depend how much model you define, if you have only 1 to 5 class model, just put it into single file, but if you have more than 5 class model, i suggesting put it on several files,这取决于你定义了多少模型,如果你只有1到5个类模型,就把它放在一个文件中,但如果你有5个以上的类模型,我建议把它放在几个文件中,

but in my experience, if the model put in a serveral files, it become little cumbersome when it comes to importing stuff,但根据我的经验,如果模型放入多个文件,导入东西时会变得不那么麻烦,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM