Django配置多数据库读写与路由详解
本文详细介绍Django项目中配置和使用多个数据库的方法。涵盖在settings.py中定义DATABASES、设置默认数据库、通过app_label指定模型归属,以及编写DatabaseRouter实现读写分离和迁移控制。包含完整的路由器代码示例、migrate命令用法及手动指定数据库的操作技巧,解决跨库保存主键冲突问题。
部分项目场景下需要同时操作多个数据库,实现这一目标的方法十分直接。
第一步是在settings配置文件中定义DATABASES变量。
假设项目需要连接两个不同的数据库,配置示例如下。
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'
}
}
通过上述配置,我们定义了两个数据库连接,分别命名为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'
}
}
一旦default被设为空,意味着系统不存在默认数据库。此时,必须为所有Model(包括引用的第三方库中的Model)明确指定数据库路由,否则无法执行操作。
第二步,为需要指定数据库的Model添加app_label属性。
class MyUser(models.Model):
...
class Meta:
app_label = 'users'
第三步,编写Database Router(数据库路由器)。
Database Router用于决定每个Model使用哪个数据库,主要需要实现以下四个方法。
db_for_read(model, **hints)
db_for_read方法:决定Model数据的读取来源数据库。
db_for_write(model, **hints)
db_for_write方法:决定Model数据的写入目标数据库。
allow_relation(obj1, obj2, **hints)
allow_relation方法:判断obj1和obj2之间是否允许建立关联,主要用于处理Foreign Key和Many-to-Many关系。
allow_migrate(db, app_label, model_name=None, **hints)
allow_migrate方法:判断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.py中配置DATABASE_ROUTERS变量。
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已拥有主键,若该主键未被其他记录使用则无影响;但若该主键已被占用,则可能导致数据覆盖。
针对此问题,有两种解决方法。
方法一:在保存前清除主键。
>>> p = Person(name='Fred') >>> p.save(using='first') >>> p.pk = None # Clear the primary key. >>> p.save(using='second') # Write a completely new object.
方法二:使用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使用多数据库的配置与路由方法,希望对读者有所帮助。如有疑问欢迎留言,小编会及时回复。感谢对本站的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









