Django项目models.py和app models.py [英] Django project models.py versus app models.py

查看:90
本文介绍了Django项目models.py和app models.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Django,我正在试图了解在项目中使用models.py和应用程序。从教程示例看,我在应用程序中包含一个模型定义,但是当我将这些知识应用到我自己现有的数据库时,我被卡住了。

I am learning Django and I am trying to understand the use of models.py in the project versus the application. It seems from the tutorial examples that I include a model definition in the app, but when I went to apply that knowledge to my own existing database I got stuck.

我使用的数据库(当然是一个副本),并使用inspectdb将概念模式生成为django模型。我在项目级别做了这个,然后假设我可以在该项目的应用程序中使用子模式编写应用程序。

I took a database that I use (a copy of course) and generated the conceptual schema as a django model using inspectdb. I did this at the project level, and presumed then I could write apps using subschemas in the applications for that project.

但是,在推广教程时,他们将模型定义在应用程序的model.py。如果我这样做,我会重复已经在项目层面的模型(或其中的一部分),这似乎是一个错误和维护问题。

But generalizing the tutorial, they define the model in the application's model.py. If I did that, I would be repeating the model (or part of it) that's already at the project level, which seems like a mistake and a maintenance issue.

所以在Django样式中,如何在应用程序的models.py中重新定义项目模式(或其部分)?

So how, in Django style, do I use the project schema (or parts of it) without redefining it in the application's models.py?

提前感谢。 >

Thanks in advance.

推荐答案

没有任何理由拥有项目级别模型(或项目级别视图)。您只需将功能分解为单独的应用程序。

There shouldn't be any reason to have "project level models" (or "project level views" for that matter). You just need to split the functionality into separate apps.

假设您正在为学校设计一个Intranet网站。您将有一个应用程序处理学生的帐户,另一个应用程序生成时间表,另一个应用程序生成时间表,另一个应用程序生成内部留言板等。可以导入彼此的模型(所以留言板帖子可以有一个ForeignKey字段指向学生从学生应用程序)。

Let's say you are designing an intranet website for a school. You would have one app that deals with students' accounts, and another app generating timetables, and yet another one for an internal message board, etc.. Every app defines its own models (there are no "project level models"), but apps can import each others models (so message board posts can have a ForeignKey field pointing at student from the "students" app).

另请参见 James Bennett从DjangoCon 2008的写可重用Django应用程序演示

这篇关于Django项目models.py和app models.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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