Django Multiple Databases - One not always available

白昼怎懂夜的黑 提交于 2019-12-03 16:28:16

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

blog = Blog('test') 
blog.save() #Assuming that sqlite is the default db
try:
    blog.save(using='mysql')
except NoInternetConnection:
    pass

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!