单个Django应用程序使用两个数据库 [英] Single Django App Using Two Databases

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

问题描述



到目前为止,我的Django环境中设置了3个数据库。我的一个应用程序使用路由器自动发送数据到正确的数据库 - 这很容易完成,因为这个应用程序只处理那个数据库。



但是,我有另一个应用程序使用两个不同的数据库。该应用程序控制其中之一,但从第二个数据获取数据,通过另一个应用程序完全更新。



我已经尝试向模型的Meta类添加一个任意属性,在路由器中匹配,但Django中不允许(就像我发现的那样)。



我可以提供哪些数据可以在路由器,要知道要去哪个数据库?

解决方案

如果您知道定义模型类时要使用哪个数据库,您可以向类本身添加任意属性,而不是其Meta类。在路由器中,您可以使用hasattr来查看该属性是否存在(因为它不适用于内置的模型),或者只是尝试/除外并捕获异常。


How can I configure models in Django which are being hosted in two different databases?

So far, I have 3 databases set up within my great Django environment. One of my apps uses a Router to automatically send data to the correct database -- this is easily done since this app only deals with that one database.

However, I have another app that uses two different databases. The app "controls" one of them, but gets data from a second that is updated through another application entirely.

I have tried adding an arbitrary attribute to the model's Meta class, to match against in the router, but this is not allowed in Django (as I discovered).

What data can I provide the model that can be matched against in the router, to know which database to go to?

解决方案

If you know when defining your model class which DB you want to use, you can add an arbitrary attribute to the class itself rather than its Meta class. In the router, you can then use hasattr to see if the attribute exists (since it won't for built in models), or just try/except and catch the exception.

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

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