简体   繁体   English

在django中将许多模型创建到文件models.py中是正确的

[英]In django It's correct create much models into file models.py

I am create a new web application with django but I have one question, if I need create 30 o 40 tables into data base, I need put all models into file models.py? 我正在使用django创建一个新的Web应用程序,但是我有一个问题,如果我需要在数据库中创建30 o 40个表,我需要将所有模型都放入文件models.py中吗?

So I think that this is very complicated of maintain, because this file may growa lot 所以我认为这维护起来非常复杂,因为该文件可能会增长很多

This is my question, is optimum make that? 这是我的问题,是最佳的选择吗?

You can create a models folder and have more specific files for all your models instead of just the single models.py file. 您可以创建一个models文件夹,并为所有模型包含更多特定文件,而不仅仅是单个models.py文件。

Say if you have 10 tables relating to the user and 10 more relating to a blog, instead of keeping them in models.py you can create a models folder and create a user.py file inside that folder, doing the same with all the blog models but in a blog.py file. 假设您有10个与用户相关的表,还有10个与博客相关的表,而不是将它们保留在models.py中,则可以创建一个models文件夹并在该文件夹中创建一个user.py文件,对所有博客都这样做模型,但在blog.py文件中。

File structure would move from this: 文件结构将与此不同:

app/
 |
  models.py

To this: 对此:

app/
  |
   models/
     |
      __init__.py
      user.py
      blog.py

Don't forget the include the __init__.py file in the models folder or else python won't recognize it as a package and you won't be able to import the models into other files. 不要忘记在models文件夹中包含__init__.py文件,否则python不会将其识别为包,并且您将无法将模型导入其他文件。

Also you now import the models by doing from app.models.user import someModel instead of from app.models import someModel . 同样,您现在也可以通过from app.models.user import someModel而不是from app.models import someModel

You can follow this same structure for all the files in Django such as views.py, forms.py, settings.py, etc.. 您可以对Django中的所有文件(例如views.py,forms.py,settings.py等)遵循相同的结构。

所有表都创建到models.py中,所有查询都可以写到views.py中

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

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