首页 > 解决方案 > Django multiple Project using same database tables

问题描述

I've been reading through related articles regarding using same database for multiple django projects however, I have not been able to come up with a fix yet. I've tried relative and absolute pathing when importing but it gives "attempted relative import beyond top-level package" error when I try to access parent directory.

Project 1 gets the users to write to database by filling in a form and Project 2 retrieves data written in by users from database.

I'm using Postgresql for database. I've tried writing exactly same models.py for both projects but it seems like in database they appear as separate relations/tables. E.g. for table named school in both models.py, it would look like project1_school and project2_school in Postgres database.

Is there a way to write to and read from same tables of same database?

Thank you so much in advance.

标签: djangopython-3.xdatabasepostgresqldjango-models

解决方案


我认为您可能对项目和应用程序之间的区别感到困惑。

项目与应用

项目和应用程序有什么区别?应用程序是做某事的 Web 应用程序——例如,Weblog 系统、公共记录数据库或小型投票应用程序。项目是特定网站的配置和应用程序的集合。一个项目可以包含多个应用程序。一个应用程序可以在多个项目中。

编写你的第一个 Django 应用程序,第 1 部分

因此,在您的特定情况下,我会说您的实际项目(两者)都可能是一个项目的应用程序。我认为这是一种更好的方法的主要原因是两者都将使用相同的数据,一个应用程序写入而另一个应用程序检索它。甚至可以争辩说它们实际上可能是同一个应用程序。但这可能取决于您业务的许多因素。

顺便说一句,我真的很难想象让两个项目使用同一个数据库是个好主意的情况。即使两个项目都需要共享数据,我也不会考虑在数据库上使用。我会尝试在应用程序级别解决它。但是我出于某种原因需要在数据库级别共享信息,有工具可以连接两个数据库。


推荐阅读