侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Django多数据库的实现过程详解

数据库  /  管理员 发布于 6年前   180

有些项目可能涉及到使用多个数据库的情况,方法很简单。

1.在settings中设定DATABASE

比如要使用两个数据库:

DATABASES = {  'default': {    'NAME': 'app_data',    'ENGINE': 'django.db.backends.postgresql',    'USER': 'postgres_user',    'PASSWORD': 's3krit'  },  'users': {    'NAME': 'user_data',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'priv4te'  }}

这样就确定了2个数据库,别名一个为default,一个为user。数据库的别名可以任意确定。

default的别名比较特殊,一个Model在路由中没有特别选择时,默认使用default数据库。

当然,default也可以设置为空:

DATABASES = {  'default': {},  'users': {    'NAME': 'user_data',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'superS3cret'  },  'customers': {    'NAME': 'customer_data',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_cust',    'PASSWORD': 'veryPriv@ate'  }}

这样,因为没有了默认的数据库,就需要为所有的Model,包括使用的第三方库中的Model做好数据库路由选择。

2.为需要做出数据库选择的Model规定app_label

class MyUser(models.Model):  ...   class Meta:    app_label = 'users'

3.写Database Routers

Database Router用来确定一个Model使用哪一个数据库,主要定义以下四个方法:

db_for_read(model, **hints)

规定model使用哪一个数据库读取。

db_for_write(model, **hints)

规定model使用哪一个数据库写入。

allow_relation(obj1, obj2, **hints)

确定obj1和obj2之间是否可以产生关联, 主要用于foreign key和 many to many操作。

allow_migrate(db, app_label, model_name=None, **hints)

确定migrate操作是否可以在别名为db的数据库上运行。

一个完整的例子:

数据库设定:

DATABASES = {  'default': {},  'auth_db': {    'NAME': 'auth_db',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'swordfish',  },  'primary': {    'NAME': 'primary',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'spam',  },  'replica1': {    'NAME': 'replica1',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'eggs',  },  'replica2': {    'NAME': 'replica2',    'ENGINE': 'django.db.backends.mysql',    'USER': 'mysql_user',    'PASSWORD': 'bacon',  },}

如果想要达到如下效果:

app_label为auth的Model读写都在auth_db中完成,其余的Model写入在primary中完成,读取随机在replica1和replica2中完成。

auth:

class AuthRouter(object):  """  A router to control all database operations on models in the  auth application.  """  def db_for_read(self, model, **hints):    """    Attempts to read auth models go to auth_db.    """    if model._meta.app_label == 'auth':      return 'auth_db'    return None   def db_for_write(self, model, **hints):    """    Attempts to write auth models go to auth_db.    """    if model._meta.app_label == 'auth':      return 'auth_db'    return None   def allow_relation(self, obj1, obj2, **hints):    """    Allow relations if a model in the auth app is involved.    """    if obj1._meta.app_label == 'auth' or \      obj2._meta.app_label == 'auth':      return True    return None   def allow_migrate(self, db, app_label, model_name=None, **hints):    """    Make sure the auth app only appears in the 'auth_db'    database.    """    if app_label == 'auth':      return db == 'auth_db'    return None

这样app_label为auth的Model读写都在auth_db中完成,允许有关联,migrate只在auth_db数据库中可以运行。

其余的:

import random class PrimaryReplicaRouter(object):  def db_for_read(self, model, **hints):    """    Reads go to a randomly-chosen replica.    """    return random.choice(['replica1', 'replica2'])   def db_for_write(self, model, **hints):    """    Writes always go to primary.    """    return 'primary'   def allow_relation(self, obj1, obj2, **hints):    """    Relations between objects are allowed if both objects are    in the primary/replica pool.    """    db_list = ('primary', 'replica1', 'replica2')    if obj1._state.db in db_list and obj2._state.db in db_list:      return True    return None   def allow_migrate(self, db, app_label, model_name=None, **hints):    """    All non-auth models end up in this pool.    """    return True

这样读取在随机在replica1和replica2中完成,写入使用primary。

最后在settings中设定:

DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']

就可以了。

进行migrate操作时:

$ ./manage.py migrate$ ./manage.py migrate --database=users

migrate操作默认对default数据库进行操作,要对其它数据库进行操作,可以使用--database选项,后面为数据库的别名。

与此相应的,dbshell,dumpdata,loaddata命令都有--database选项。

也可以手动的选择路由:

查询:

>>> # This will run on the 'default' database.>>> Author.objects.all() >>> # So will this.>>> Author.objects.using('default').all() >>> # This will run on the 'other' database.>>> Author.objects.using('other').all()

保存:

>>> my_object.save(using='legacy_users')

移动:

>>> p = Person(name='Fred')>>> p.save(using='first') # (statement 1)>>> p.save(using='second') # (statement 2)

以上的代码会产生问题,当p在first数据库中第一次保存时,会默认生成一个主键,这样使用second数据库保存时,p已经有了主键,这个主键如果未被使用不会产生问题,但如果先前被使用了,就会覆盖原先的数据。

有两个解决方法;

1.保存前清除主键:

>>> p = Person(name='Fred')>>> p.save(using='first')>>> p.pk = None # Clear the primary key.>>> p.save(using='second') # Write a completely new object.

2.使用force_insert

>>> p = Person(name='Fred')>>> p.save(using='first')>>> p.save(using='second', force_insert=True)

删除:

从哪个数据库取得的对象,从哪删除

>>> u = User.objects.using('legacy_users').get(username='fred')>>> u.delete() # will delete from the `legacy_users` database

如果想把一个对象从legacy_users数据库转移到new_users数据库:

>>> user_obj.save(using='new_users')>>> user_obj.delete(using='legacy_users')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    django迁移数据库错误问题解决
    下一条:
    Django 迁移、操作数据库的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客