A, Django database configuration
(A) modify settings.py file on the database configuration:
Django default sqlite:
# Django default database library, SQLit configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # sqlite引擎 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
Add a database: modeled on the "default" format directly add:
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'), }, }
Note: If you want to use mysql, you need to be configured:
settings.py 1. edit the project folder
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # mysql engine 'NAME': 'BookManagement', # Database name, you need the command 'CREATE DATABASE BookManagement' created in advance mysql command window 'USER': 'root', # database user name 'PASSWORD': 'xxx', # password database without a password or an empty string 'HOST': '', # database host, the default is localhost blank 'PORT': '3306', # database port } }
2. __init__.py edit the project folder: mysql default drive is due MySQLdb in Django, and the driver does not apply to python3, therefore, we need to change the drive to PyMySQL
# Code: import pymysql pymysql.install_as_MySQLdb()
3. Display the SQL statement, we said earlier ORM is a high-level object-oriented operation, is converted to low-level SQL statement, if you want to print the corresponding SQL statements in the terminal, you can add logging in setting.py
Code: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } }
(B), after modifying the good database configuration, create tables in models.py file, followed by database migration work:
python manage.py makemigrations # generated record migrations folder, pre-migration checks python manage.py migrate # actually perform database migration command, create the table after this command is executed
Second, separate read and write
(A) manually separate read and write
1. When using a database, is specified by manually .using (db_name) to use a database
Advantages: no need for the rest of the configuration, only by .using (db_name) to manually specify the database to be used on the line.
Disadvantage: after a large number of database operations, such methods cumbersome
# Code from django.shortcuts import HttpResponse from . import models def write(request): models.Products.objects.using('default').create(prod_name='熊猫公仔', prod_price=12.99) return HttpResponse ( 'write success') def read(request): obj = models.Products.objects.filter(id=1).using('db2').first() return HttpResponse(obj.prod_name)
(B) automatically separate read and write
Routed through the configuration database to automatically, thereby eliminating the need to manually specify the database every time the reader. Routing database provides four methods. Here there is mainly used two of them: def db_for_read () determine the database read operation, def db_for_write () decide database writes.
Router definition of class
New myrouter.py
script to define Router categories:
class Router: def db_for_read(self, model, **hints): return 'db2' def db_for_write(self, model, **hints): return 'default'
Configure Router
In settings.py
specified inDATABASE_ROUTERS
DATABASE_ROUTERS = ['myrouter.Router',]
Multi scheme from a primary
Read performance of the website is usually more important, therefore, can be more than a few configuration database, and when reading, randomly selected, such as:
class Router: def db_for_read(self, model, **hints): """ Randomly selecting a database to read """ import random return random.choice(['db2', 'db3', 'db4']) def db_for_write(self, model, **hints): """ Select the primary library writing """ return 'default'
Sub-library sub-table
In large web projects, often create multiple app to handle different business, if you want to implement database separation between the app, such as go app01 database db1, app02 go database
class Router: def db_for_read(self, model, **hints): if model._meta.app_label == 'app01': return 'db1' if model._meta.app_label == 'app02': return 'db2' def db_for_write(self, model, **hints): if model._meta.app_label == 'app01': return 'db1' if model._meta.app_label == 'app02':
Transfer from https://blog.csdn.net/Ayhan_huang/article/details/78784486