Django多个数据库-一个并不总是可用 [英] Django Multiple Databases - One not always available

查看:62
本文介绍了Django多个数据库-一个并不总是可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发将使用多个数据库后端的Django应用程序.我想在运行django应用程序的计算机上放置一个sqlite数据库,并同步到远程mysql数据库.棘手的部分是,运行该应用程序的计算机将不总是具有Internet连接,因此mysql数据库并不总是可用.将有多台计算机运行该应用程序,每台计算机都具有自己的本地sqlite DB,但所有计算机都使用相同的远程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.

我还没有编写代码,但是这是我要记住的.每次运行插入或更新时,我都希望将其写入两个数据库,除非远程数据库不可用,在这种情况下,我会将sql语句保存在本地数据库的表中,以便在远程数据库可用时运行.

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.

这可以通过数据库路由器完成吗,还是需要在每个db语句中手动实现?

Can this be done with database routers, or do I need to manually implement this with each db statement?

关于PK的说明:没有直接关系,但一定要询问.主密钥将在每台计算机上本地生成.在mysql DB中,将有一个用于该密钥的字段,以及一个具有应用程序每个实例的唯一标识符的字段,这些字段一起将提供一个唯一的密钥.

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.

推荐答案

我获取了DrDee的代码,并将其附加到post_save信号上(帮助为+1).

I took DrDee's code and attached it to the post_save signal (+1 for the help).

@receiver(models.signals.post_save) #new signal decorator in Django 1.3
def save_to_remote(sender,instance,using,**kwargs):
    if using == 'default' and instance.__module__ == 'mymodel.myapp.models':
        try:
            instance.save(using='remote')
        except:
            pending_instance=Pending_Remote(
                                            pk_default=instance.pk,
                                            model_default=instance.__class__.__name__
                                            )
            pending_instance.save()

这还将保存未保存到远程数据库的记录.请注意,模型Pending_Remote不得位于"myapp"中.

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

这篇关于Django多个数据库-一个并不总是可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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