自定义Django数据库后端报错:需实现quote_name()方法
自定义Django数据库后端重写JSON处理时遭遇NotImplementedError
问题场景
为重写SQLite3和Postgres的JSON处理逻辑,尝试自定义数据库后端,操作步骤如下:
- 在应用目录创建
backends文件夹 - 编写
base.py代码:
from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.sqlite3.base import DatabaseWrapper as DBW import json class BaseDatabaseOperationsJSON(BaseDatabaseOperations): def adapt_json_value(self, value, encoder): print("should be called") return json.dumps(value, ensure_ascii = False, cls = encoder) class DatabaseWrapper(DBW): ops_class = BaseDatabaseOperationsJSON
- 修改
settings.py中的数据库引擎配置:
DATABASES = { 'default': { 'ENGINE': "Shelf.backends.sqlite3json", 'NAME': BASE_DIR.joinpath("db.sqlite3"), } }
配置完成后触发错误:
NotImplementedError: subclasses of BaseDatabaseOperations may require a quote_name() method
解决方法
问题根源在于你直接继承了BaseDatabaseOperations基类,该类的quote_name是未实现的抽象方法,必须在子类中重写,或直接继承对应数据库的专属Operations类而非基类。
针对SQLite3场景,应继承django.db.backends.sqlite3.operations.DatabaseOperations,这样就能复用SQLite3已实现的所有方法(包括quote_name),仅重写需要自定义的adapt_json_value即可。修改后的base.py代码如下:
from django.db.backends.sqlite3.operations import DatabaseOperations as SQLiteDBOps from django.db.backends.sqlite3.base import DatabaseWrapper as DBW import json class CustomSQLiteOperations(SQLiteDBOps): def adapt_json_value(self, value, encoder): print("should be called") return json.dumps(value, ensure_ascii=False, cls=encoder) class DatabaseWrapper(DBW): ops_class = CustomSQLiteOperations
如果是Postgres场景,同理只需继承django.db.backends.postgresql.operations.DatabaseOperations,再重写adapt_json_value方法即可。
此修改可避免quote_name未实现的错误,同时让自定义JSON处理逻辑正常生效。
内容的提问来源于stack exchange,提问作者xtlc
相关产品推荐
相关产品推荐

