定义多个数据库
DATABASES = {
'default': {
'NAME': 'test01',
'ENGINE': 'django.db.backends.postgresql',
'USER': 'postgres_user',
'PASSWORD': '123456'
},
'db02': {
'NAME': 'test02',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'PASSWORD': '123456'
}
}
同步指定数据库
./manage.py migrate --database=db02
ORM写法
>>>
>>> Author.objects.all()
>>>
>>> Author.objects.using('default').all()
>>>
>>> Author.objects.using('db02').all()
save和delete操作
>>> my_object.save(using='db02')
>>> u = User.objects.using('db02').get(username='fred')
>>> u.delete()
使用原生sql
from django.db import connections
cursor = connections['db02'].cursor()
cursor.execute(sql)
result = cursor.fetchall()
with connections['db02'].cursor() as cursor:
...
其他
数据库路由、管理器管理多个数据库等,可参考 https://docs.djangoproject.com/en/4.0/topics/db/multi-db/
|