基于模型表的Django路由到数据库 [英] Django routing to database based on model table

查看:141
本文介绍了基于模型表的Django路由到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个数据库的Django(1.6)项目。我有一个应用程序与一个模型,和多个表。



我想使用数据库路由器将模型中的特定表设置为特定的数据库。我发现的所有文档似乎解释了如何将特定应用程序路由到特定的数据库。

解决方案

看起来你可以使用



YMMV:没有测试过这个。



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

  class MyModel(models.Model):
_DATABASE =foo

class CustomRouter(object):
def db_for_read(self,model,** hints):
database = getattr(model,_DATABASE没有)
返回数据库
#重复db_for_write等


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.

解决方案

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.

这篇关于基于模型表的Django路由到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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