【问题标题】:Perform all write operations using one DB with Django multiple databases使用一个 DB 和 Django 多个数据库执行所有写入操作
【发布时间】:2012-02-06 08:44:40
【问题描述】:

在我的 django 应用中,我有一个使用这种方法的模型:

def deleteItem(self, item, pt):
        if pt == 'product':
            i = self.vcartitem_set.filter(product__id=item)
        elif pt == 'brand':
            i = self.vcartbrand_set.filter(brand__id=item)
        else:
            return u'Wrong product type'
        i.delete()
        return 'OK'

我有 2 个数据库,“默认”和“从属”。从属是只读的,所以当 self.vcartitem_set.filter(product__id=item) 使用 'slave' 数据库执行时,我在 i.delete() 上出现错误.我可以通过编写 i.delete(using='default') 来绕过它,但是我必须为每个模型编写它。有没有办法告诉 django 使用“默认”数据库执行所有写入操作,即使之前使用“从”数据库检索到对象?

【问题讨论】:

    标签: database django multiple-databases


    【解决方案1】:

    您可以使用 DB 路由器执行此操作:
    https://docs.djangoproject.com/en/dev/topics/db/multi-db/#automatic-database-routing

    您只需要创建一个路由器模型并定义 db_for_read 和 db_for_write 函数,将 DATABASE_ROUTERS 添加到您的 settings.py 中即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-04
      • 2020-11-24
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多