刘沙河 刘沙河
首页
  • Go语言基础

    • 数据类型
    • 反射
    • Go指针
  • Go语言进阶

    • go泛型
    • go条件编译
    • cgo教程
    • Go协程调度原理及GPM模型
    • Go内存管理
    • Go垃圾回收机制
    • Go语言内存对齐
  • Go语言实现原理

    • channel 实现原理
    • slice 实现原理
    • map 实现原理
    • sync.Mutex 实现原理
    • 乐观锁CAS 实现原理
    • singlefight 实现原理
  • gin框架

    • gin中间件原理
    • gin路由原理
  • gorm

    • GORM介绍和使用
    • GORM_CURD操作指南
  • go测试

    • benchmark基准测试
    • pprof 性能分析
  • python进阶

    • Numpy&Pandas
    • celery分布式任务队列
  • Django

    • Django 常见命令
    • middleware中间件
    • Django缓存系统
    • Django信号系统
    • Django REST Framework
  • Flask

    • Flask基础知识总结
    • Flask-SQLAlchemy
  • 爬虫

    • aiohttp
    • scrapy框架
  • Mysql

    • Mysql存储引擎和索引
    • MySQL主从复制
    • Mysql读写分离
    • 数据库分库分表
    • Mysql锁
    • Mysql事务和MVCC原理
    • 分库分表带来的读扩散问题
  • Redis

    • redis基础和数据类型
    • redis主从架构
    • redis哨兵架构
    • redis集群模式
    • 如何保证缓存和数据库双写一致
    • redis底层数据结构
    • redis分布式锁
  • Elasticsearch

    • es基本概念
    • es基础语法
    • es倒排索引
  • etcd

    • Go操作etcd
    • Raft原理
    • etcd分布式锁
  • kafka

    • 消息队列MQ总结
    • kafka 概述及原理
    • kafka 消费问题记录
    • 零拷贝技术
    • kafka分区规范
  • RabbitMQ

    • rabbitMQ基础
    • Go操作rabbitmq
  • RocketMQ

    • 可靠消息队列 rocketMQ
  • Http&Https

    • http&https
    • TCP和UDP
    • Ping 原理
  • RPC

    • RPC初识
    • grpc初识和实现
  • gRPC

    • grpc 初识
    • grpc 上下文 metadata
    • grpc 健康检查
    • grpc keepalive
    • grpc 命名解析
    • grpc 中间件&拦截器
    • grpc 负载均衡
    • grpc 身份认证
    • grpc 超时重试
    • grpc 链路追踪
    • grpc-gw将gRPC转RESTfu api
    • grpc-gw自定义选项
  • protobuf

    • protobuf 进阶
    • protobuf 编码原理
  • Docker

    • Docker基础
    • Docker常用命令
    • Dockerfile
    • Docker-Compose
    • Docker多阶段构建
    • Docker Config 教程
    • Docker Swarm 教程
    • Docker Stack 教程
    • Docker Buildx 教程
  • k8s

    • k8s 基础概念
    • k8s 集群架构
    • k8s 工作负载
    • Pod 网络
    • Service 网络
    • 外部接入网络
    • 一张图搞懂k8s各种pod
    • k8s 存储抽象
    • mac快速启动k8s
    • 自制申威架构k8s-reloader
  • go-kit

    • go-kit初识
    • go-kit启动http服务
    • go-kit集成gin启动服务
    • go-kit集成grpc和protobuf
    • go-kit中间件
    • go-kit服务注册发现与负载均衡
    • go-kit限流和熔断
    • go-kit链路追踪
    • go-kit集成Prometheus
  • 设计模式

    • 初识设计模式
    • 创建型模式
    • 结构型模式
    • 行为模式
  • 数据结构

    • 时间轮
    • 堆、双向链表、环形队列
    • 队列:优先队列
    • 队列:延迟队列
  • 算法

    • 递归算法
    • 枚举算法
    • 动态规划
    • 回溯算法
    • 分治算法
    • 贪心算法
    • LRU和LFU
    • 一致性哈希

花开半夏,半夏花开
首页
  • Go语言基础

    • 数据类型
    • 反射
    • Go指针
  • Go语言进阶

    • go泛型
    • go条件编译
    • cgo教程
    • Go协程调度原理及GPM模型
    • Go内存管理
    • Go垃圾回收机制
    • Go语言内存对齐
  • Go语言实现原理

    • channel 实现原理
    • slice 实现原理
    • map 实现原理
    • sync.Mutex 实现原理
    • 乐观锁CAS 实现原理
    • singlefight 实现原理
  • gin框架

    • gin中间件原理
    • gin路由原理
  • gorm

    • GORM介绍和使用
    • GORM_CURD操作指南
  • go测试

    • benchmark基准测试
    • pprof 性能分析
  • python进阶

    • Numpy&Pandas
    • celery分布式任务队列
  • Django

    • Django 常见命令
    • middleware中间件
    • Django缓存系统
    • Django信号系统
    • Django REST Framework
  • Flask

    • Flask基础知识总结
    • Flask-SQLAlchemy
  • 爬虫

    • aiohttp
    • scrapy框架
  • Mysql

    • Mysql存储引擎和索引
    • MySQL主从复制
    • Mysql读写分离
    • 数据库分库分表
    • Mysql锁
    • Mysql事务和MVCC原理
    • 分库分表带来的读扩散问题
  • Redis

    • redis基础和数据类型
    • redis主从架构
    • redis哨兵架构
    • redis集群模式
    • 如何保证缓存和数据库双写一致
    • redis底层数据结构
    • redis分布式锁
  • Elasticsearch

    • es基本概念
    • es基础语法
    • es倒排索引
  • etcd

    • Go操作etcd
    • Raft原理
    • etcd分布式锁
  • kafka

    • 消息队列MQ总结
    • kafka 概述及原理
    • kafka 消费问题记录
    • 零拷贝技术
    • kafka分区规范
  • RabbitMQ

    • rabbitMQ基础
    • Go操作rabbitmq
  • RocketMQ

    • 可靠消息队列 rocketMQ
  • Http&Https

    • http&https
    • TCP和UDP
    • Ping 原理
  • RPC

    • RPC初识
    • grpc初识和实现
  • gRPC

    • grpc 初识
    • grpc 上下文 metadata
    • grpc 健康检查
    • grpc keepalive
    • grpc 命名解析
    • grpc 中间件&拦截器
    • grpc 负载均衡
    • grpc 身份认证
    • grpc 超时重试
    • grpc 链路追踪
    • grpc-gw将gRPC转RESTfu api
    • grpc-gw自定义选项
  • protobuf

    • protobuf 进阶
    • protobuf 编码原理
  • Docker

    • Docker基础
    • Docker常用命令
    • Dockerfile
    • Docker-Compose
    • Docker多阶段构建
    • Docker Config 教程
    • Docker Swarm 教程
    • Docker Stack 教程
    • Docker Buildx 教程
  • k8s

    • k8s 基础概念
    • k8s 集群架构
    • k8s 工作负载
    • Pod 网络
    • Service 网络
    • 外部接入网络
    • 一张图搞懂k8s各种pod
    • k8s 存储抽象
    • mac快速启动k8s
    • 自制申威架构k8s-reloader
  • go-kit

    • go-kit初识
    • go-kit启动http服务
    • go-kit集成gin启动服务
    • go-kit集成grpc和protobuf
    • go-kit中间件
    • go-kit服务注册发现与负载均衡
    • go-kit限流和熔断
    • go-kit链路追踪
    • go-kit集成Prometheus
  • 设计模式

    • 初识设计模式
    • 创建型模式
    • 结构型模式
    • 行为模式
  • 数据结构

    • 时间轮
    • 堆、双向链表、环形队列
    • 队列:优先队列
    • 队列:延迟队列
  • 算法

    • 递归算法
    • 枚举算法
    • 动态规划
    • 回溯算法
    • 分治算法
    • 贪心算法
    • LRU和LFU
    • 一致性哈希
  • Python基础

  • Python进阶

  • Python并发编程

  • Django

    • django 常见命令
    • Django模板母版
    • Django视图
    • Django路由系统
    • Django--orm系统-指令&属性
    • Django--orm系统 -分组聚合
    • Django-cookie&session
    • middleware中间件
    • Django 的身份认证系统
    • Django models 之字段详解
    • Django缓存系统
    • Django数据库系统
      • 一 常见数据库连接配置
        • 1. mysql
        • 2. pg
        • 3. sqllite
      • 二 多数据库配置
        • 1. orm 性能优化
        • 2. 配置多个数据库连接
        • 3. django 执行原生sql
      • 三 读写分离
        • 1. 手动
        • 2. 自动
    • Django信号系统
    • Django序列化和反序列化
    • Django中admin用法
    • DRF 版本、认证、权限、限制、解析器和渲染器
    • DRF(Django REST Framework)框架
  • Flask

  • 爬虫

  • Python
  • Django
bigox
2021-07-05
目录

Django数据库系统

# Django 数据库系统

# 一 常见数据库连接配置

# 1. mysql

  • settings

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'day54',
            'HOST':'127.0.0.1',
            'PORT':3306,
            'USER':'root',
            'PASSWORD':'123'
        }
    }
    # ps:键必须都是大写
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
  • init

    方式1:在你的项目文件夹下面的__init__.py
    方式2:也可以在你的应用文件夹下面的__init__.py
    # 固定写法
    import pymysql
    pymysql.install_as_MySQLdb()  # 告诉django用pymysql代替mysqldb连接数据库
    
    1
    2
    3
    4
    5

# 2. pg

  • settings

    模块依赖pip install psycopg2-binary==2.9.1

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'webserver',
            'USER': 'webserver',
            'PASSWORD': 'Webserver123!',
            'HOST': '10.0.23.109',
            'PORT': 5432,
            'OPTIONS': {  # 该参数是为了指定你的 schema 
                'options': '-c search_path=scbd'
            }
        },
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

# 3. sqllite

  • settings 默认

        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
    
    1
    2
    3
    4

# 二 多数据库配置

# 1. orm 性能优化

  1. 尽量不查对象,能用values()

  2. select_related('classes') 连表查询 多对一 一对一

  3. prefetch_related('classes') 子查询 多对一 多对多

  4. only('name') 指定某些字段 defer 指定排除某些字段

# 2. 配置多个数据库连接

  • settings 配置

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
        'db2': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
        },
        'db3': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db3.sqlite3'),
        },
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  • 迁移指定的数据库

    python manage.py migrate --database db2
    
    1

# 3. django 执行原生sql

  • extra

    #解释:结果集修改器,一种提供额外查询参数的机制
    #说明:依赖model模型
    #用在where后:
    Book.objects.filter(publisher_id="1").extra(where=["title='python学习1'"])    
    #用在select后  
    Book.objects.filter(publisher_id="1").extra(select={"count":"select count(*) from hello_book"})
    
    1
    2
    3
    4
    5
    6
    ret = models.Student.objects.all().extra(where=['id > %s'], params=['1'], order_by=['-id'])
    # print(ret)
    # for i in ret:
    #     print(i)
    
    1
    2
    3
    4
  • row

    ret = models.Student.objects.raw('select * from main.app01_classes where id <= 2')
    print(ret)
    for i in ret:
        print(i.name)
    
    1
    2
    3
    4
  • connection

    
    from django.db import connection, connections
    
    # cursor = connection.cursor()
    cursor = connections['db2'].cursor()
    cursor.execute("""SELECT * from main.app01_classes where id > %s""", [1])
    row = cursor.fetchall()
    print(row)
    
    1
    2
    3
    4
    5
    6
    7
    8
    from django.db import connection
    cursor = connection.cursor()
    #插入
    cursor.execute("insert into hello_author(name) values('xiaol')")
    #更新
    cursor.execute("update hello_author set name='xiaol' where id=1")
    #删除
    cursor.execute("delete from hello_author where name='xiaol'")
    #查询
    cursor.execute("select * from hello_author")
    #返回一行
    raw = cursor.fetchone()
    print(raw)
    # #返回所有
    # cursor.fetchall()
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

# 三 读写分离

# 1. 手动

models.Student.objects.using('db2').all()

obj = models.Student.objects.using('db2').get(name='zhazha')
obj.name = 'star'
obj.save(using='default')
1
2
3
4
5

# 2. 自动

  • settings配置:

    DATABASE_ROUTERS = ['myrouter.Router']
    
    1
  • 自定义Router类

    class Router:
        """
        读写分离
        """
    
        def db_for_write(self, model, **kwargs):
            return 'db2'
    
        def db_for_read(self, model, **kwargs):
            return 'default'
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  • 一主多从

    class Router:
        """
        一主多从
        """
    
        def db_for_write(self, model, **kwargs):
            return 'db1'
    
        def db_for_read(self, model, **kwargs):
            return random.choices['db2', 'db3', 'db4']
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  • 分库分表

    class Router:
        """
        分库分表
    
        app01  model   db1
        app02  model   db2
        """
    
        def db_for_write(self, model, **kwargs):
            app_name = model._meta.app_label
            if app_name == 'app01':
                return 'db1'
            elif app_name == 'app02':
                return 'db2'
    
        def db_for_read(self, model, **kwargs):
            app_name = model._meta.app_label
            if app_name == 'app01':
                return 'db1'
            elif app_name == 'app02':
                return 'db2'
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
#Python#
上次更新: 2023/04/16, 18:35:33
Django缓存系统
Django信号系统

← Django缓存系统 Django信号系统→

最近更新
01
go与http代理
05-24
02
自制申威架构k8s-reloader
12-06
03
Docker Buildx 教程
12-01
更多文章>
Theme by Vdoing | Copyright © 2020-2024 小刘扎扎 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式