Django数据库路由器 [英] Django database router

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

问题描述

我想根据经过身份验证的用户路由(更改)数据库。我查看了 docs ,但我没有不知道如何在用户登录时执行此操作...

I'd like to route (change) the database based on the authenticated user. I've looked at the docs but I don't know how to do this upon user login...

我正在考虑添加一个字段与 database_name 我的自定义 UserProfile 然后我想传递这个信息到数据库路由器,这将使交换机...

I was thinking of adding a field with database_name to my custom UserProfile and then I'd like to pass this info to the database router which would make the switch...

我没有任何代码可以显示,因为我根本不知道如何实现这个。

I don't have any code to show because I simply don't know how to implement this.

这个帖子与我之前的邮箱

所以模式如下所示:

- Users (containing only the `UserProfile`)
 - user1 (containing the app database)
 - user2 (containing the app database)
 - ...

你能指点我吗正确的方向?

Could you point me to the right direction?

谢谢!
BR

Thank you! BR

推荐答案

请参阅这个的帖子如何玩路由器

Refer to this post on how to play around with the routers

DATABASE_ROUTERS = ['CustomDatabaseRouter',] #a setting that Django understands.

class CustomDatabaseRouter(object):

  def db_for_read(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def db_for_write(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def allow_syncdb(self, model, **hints):
     site_name = get_current_site()
     if site_name in ['site1'] and db == 'db1':
         return True
     if site_name in ['site2'] and db == 'db2':
        return True
     return False

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

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