django一个应用程序一个模型多个数据库 [英] django one app one model multiple databases

查看:151
本文介绍了django一个应用程序一个模型多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我是django webapp开发的新手,但我遇到了问题.我创建了1个具有1个模型的应用程序,以使用1个表单将数据插入数据库.我将为此使用多个数据库.每个数据库将有1个结构相同的表(目前).现在我的问题是:

如何为多个数据库及其各自的表仅使用1个模型,1个视图和1个表格.数据库和表应在调用它们各自的URL时进行切换.

例如 http://www.example.com/x/abc/将访问第一个数据库,并且所有操作的表格.
http://www.example.com/y/abc/将访问第二个数据库

我已经尝试了django文档中提供的示例数据库路由,但是并没有太大帮助.我也找不到相对的帖子/问题来解决这个特定问题


I am new to django webapp development and i am stuck with a problem. I have created 1 app with 1 model to insert data to the database using 1 form. I am going to use multiple databases for this. Each database will have 1 table(for now) with same structure. Now my problem is:

How can I use just 1 model, 1 view and 1 form for multiple databases and their respective tables. Databases and tables should be switched on calling their respective urls.

e.g. http://www.example.com/x/abc/ will access first database and it's tables for all the operations.
http://www.example.com/y/abc/ will access second database

I have already tried the sample db routing provided in django documentation, but it doesn't help much. also I couldn't find a relative post/question which addresses this particular problem

我想这样做是因为以后我将添加更多模型和表格来访问数据库表中的数据,这对我来说似乎是最干净的方法

I want to do this because later i will add more models and forms for accessing the data from the database tables and this seems the cleanest way to me

PS:我正在使用Django 1.9.6

PS: I am using django 1.9.6

推荐答案

不管这是否是构建应用程序的好方法,您都可以使用告诉Django使用读写哪个数据库>:

Regardless of whether or not this is a good way to architect your application, you can tell Django which database to read and write with using:

Person.objects.using('db1').create(...)
Person.objects.using('db2').create(...)

因此,您无需使用路由器,只需在设置中定义两个数据库,然后在两个数据库上都运行 migrate .将在每个数据库中创建模型的表,并在代码中根据您选择的任何逻辑(例如,基于请求路径)从两个数据库进行读写.

So you don't need to use a router, simply define the two database in your settings and run migrate on both. Your model's table will be created in each database, and in your code you can read and write from the two database based on any logic you choose (e.g. based on the request path).

请参见 https://docs.djangoproject.com/zh-CN/1.9/topics/db/multi-db/#manually-selecting-a-database

这篇关于django一个应用程序一个模型多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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