Django 多个数据库 - 一个并不总是可用
我正在开发一个 Django 应用程序,它将使用多个数据库后端。我想在运行 django 应用程序的机器上放置一个 sqlite 数据库,并同步到远程 mysql 数据库。棘手的部分是,运行应用程序的机器并不总是有互联网连接,因此 mysql 数据库并不总是可用。将有多台机器运行该应用程序,每台机器都有自己的本地 sqlite DB,但都使用相同的远程 mysql DB。
我还没有编写代码,但这就是我的想法。每次运行插入或更新时,我都想将其写入两个数据库,除非远程数据库不可用,在这种情况下,我会将sql语句保存在本地数据库上的表中,以便在远程数据库可用时运行。
这可以通过数据库路由器来完成吗?还是我需要用每个数据库语句手动实现这一点?
关于PK的注意事项:没有直接关系,但肯定会被问到。主键将在每台机器上本地生成。在 mysql DB 中,将有一个用于此键的字段,以及一个为应用程序的每个实例提供唯一标识符的字段,它们一起将提供唯一的键。
I am developing a Django application which will use multiple database backends. I would like to put an sqlite database on the machine running the django application, and sync to a remote mysql database. The tricky part is that this machine running the application will not always have an internet connection, so the mysql database is not always availalble. There will be multiple machines running the application, each with it's own local sqlite DB, but all using the same remote mysql DB.
I haven't written the code yet, but here is what I have in mind. Every time I run an insert or update I would like to write it to both databases, unless the remote DB is unavailable, in which case I will save the sql statement in a table on the local database to run when the remote DB is available.
Can this be done with database routers, or do I need to manually implement this with each db statement?
Note on PK: Not directly related, but sure to be asked. The primary key will be generated locally on each machine. In the mysql DB there will be a field for this key, and a field with a unique identifier for each instance of the application, which together will provide a unique key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您有一个名为 Blog 的模型,那么您可以使用以下命令将其存储在本地和远程(假设您已配置对远程数据库的访问)。
确保您已在 settings.py 中定义并配置了“mysql”,并且处理了没有 Internet 连接的情况。
旁注:我不太确定你为什么要这样做。如果这是出于备份目的,那么我将使用标准备份程序。有关使用多个数据库的更多信息,请参阅:http://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-raw-cursors-with-multiple-databases
Suppose you have a model called Blog then you can use the following to store it locally and remotely (assuming that you have configured access to the remote db).
Make sure you have defined and configured 'mysql' in settings.py and that you handle the cases when there is no Internet connection.
Side note: I am not quite sure why you actually would want to do this. If this is for backup purposes then I would use standard backup procedures. For more information about using multiple databases see: http://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-raw-cursors-with-multiple-databases
我获取了 DrDee 的代码并将其附加到 post_save 信号(+1 以获得帮助)。
这还会保存未保存到远程数据库的记录。请注意,模型 Pending_Remote 不得位于“myapp”中。
I took DrDee's code and attached it to the post_save signal (+1 for the help).
This also saves a record of what was not saved to the remote database. Note that the model Pending_Remote must not be in 'myapp'.