Django routing to database based on model table

核能气质少年 提交于 2019-12-11 15:33:07

问题


I have a Django (1.6) project with two databases. I have one app with one model, and multiple tables.

I want to use the database routers to set specific tables in the model to a specific database. All the documentation I have found seems to explain how to route a particular app to a particular database.


回答1:


Looks like you could use a custom router and model attribute for this.

YMMV: Haven't tested this.

https://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-routers

class MyModel(models.Model):
    _DATABASE = "foo"

class CustomRouter(object):
    def db_for_read(self, model, **hints):
      database = getattr(model, "_DATABASE", None)
      return database
    # repeat for db_for_write, etc.


来源:https://stackoverflow.com/questions/19905476/django-routing-to-database-based-on-model-table

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