Django数据库配置
Django数据库配置
1、使用非公共架构(非public)
可以通过 OPTIONS
参数指定 postgresql 数据库使用的架构。
'options': '-c search_path=jg'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'postgres',
'PASSWORD': 'sone',
'HOST': 'localhost',
'PORT': '5432',
'OPTIONS': {
'options': '-c search_path=jg'
# 'options': '-c search_path=jg,public'
}
}
}
不指定 options search_path 参数时,默认使用 public 架构。
search_path
:查找顺序。当指定多个架构时,依次查找,找到后就不再向下查找。
search_path=jg
表示使用 jg 架构,而不默认的 public 架构。search_path=jg,public
表示依次查找 jg,public 构架及表。
- 1)查找架构:如果 jg 存在,则停止查找;如果不存在,则继续查找 public 架构。
- 2)查找表:即便 jg、public 都存在,如果在 jg 中找不到要找到表,也会继续在 public 中查找。
2、配置多个数据库
2.1 settings.py 配置多个数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'postgres',
'PASSWORD': 'sone',
'HOST': 'localhost',
'PORT': '5432',
'OPTIONS': {
'options': '-c search_path=jg,public'
}
},
'db2': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'udb',
'USER': 'postgres',
'PASSWORD': 'sone',
'HOST': 'localhost',
'PORT': '5432',
}
}
2.2 创建数据库路由规则
在 settings.py 同级目录下创建 database_router.py
文件
# -*- coding: utf-8 -*-
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING
class DatabaseAppsRouter(object):
"""
A router to control all database operations on models for different
databases.
In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
will fallback to the `default` database.
Settings example:
DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
"""
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
"""Allow any relation between apps that use the same database."""
db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
if db_obj1 and db_obj2:
if db_obj1 == db_obj2:
return True
else:
return False
return None
# for Django 1.4 - Django 1.6
def allow_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in DATABASE_MAPPING:
return False
return None
# Django 1.7 - Django 1.11
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
2.3 settings.py 中为每个 app 配置对应的数据库
# DATABASE_ROUTERS = ['project_name.database_router.DatabaseAppsRouter']
DATABASE_ROUTERS = ['djpros.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
#'app_name':'database_name',
'emp': 'default',
'cls': 'db2',
}
2.4 迁移
工程目录结构:
执行迁移:
python manage.py makemigrations
执行 migrate 时略有不同,需要注意:
执行
python manage.py migrate
时:
default 配置库对应的 app 会在数据库中生成相应的表,而其他的配置库不会在数据库中生成表。
所以,执行migrate
应该分别迁移对相应的数据库:python manage.py migrate --database=db1 python manage.py migrate --database=db2 ......
- 执行
migrate
python manage.py migrate # 在 mydb 库下的 jg 模式中生成 emp_emp 表
python manage.py migrate --database=db2 # 在 udb 库下的 public 模式中生成 cls_scls 表
2.5 views 中查询表数据
# 查询
Emp.objects.using('default').all()
Scls.objects.using('db2').all()
# 保存 或 删除
user_obj.save(using='default')
user_obj.delete(using='db2')
3、django 数据库数据导入导出
- 数据导出
python manage.py dumpdata emp --database=default > emp.json
导出数据的格式为:
[{"model": "emp.emp", "pk": 1, "fields": {"uname": "tom", "deptno": 100, "deptname": "\u5f00\u53d1\u90e8", "salary": 5000}}]
- 数据导入
python manage.py loaddata emp.json --database=default
参考地址:
http://www.javabin.cn/2019/pgsql_schema.html
https://www.jianshu.com/p/04cd9d4f67a2
https://code.ziqiangxuetang.com/django/django-multi-database.html