Django 项目models.py 与应用程序models.py [英] Django project models.py versus app models.py

查看:32
本文介绍了Django 项目models.py 与应用程序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?

提前致谢.

推荐答案

不应该有任何理由拥有项目级模型"(或项目级视图").您只需要将功能拆分为单独的应用即可.

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 网站.你会有一个处理学生账户的应用程序,另一个生成时间表的应用程序,还有一个用于内部留言板等的应用程序.每个应用程序都定义了自己的模型(没有项目级模型"),但应用程序可以导入彼此的模型(所以留言板帖子可以有一个外键字段指向学生"应用程序中的学生).

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).

另请参阅 DjangoCon 2008 中的James Bennett 的编写可重用的 Django 应用程序"演示.

See also James Bennett's "writing reusable Django applications" presentation from DjangoCon 2008.

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

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