使用Djongo连接Django与MongoDB执行makemigrations时出错求助
问题
使用 Django 4.1.13 + Djongo 1.3.6 + MongoDB 7.0.3 搭建动态网站,配置数据库连接后执行 python manage.py makemigrations 命令时触发以下错误:
数据库配置(settings.py)
DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Cake_Bakery', 'CLIENT':{'host':'localhost','port':27017} } }
报错信息
(cake) PS D:\Cake Eccomerce\cake\Cake_Bakery> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/products' [name='products'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. No changes detected Traceback (most recent call last): File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 22, in <module> main() File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Cake Eccomerce\cake\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "D:\Cake Eccomerce\cake\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "D:\Cake Eccomerce\cake\Lib\site-packages\pymongo\database.py", line 1337, in __bool__ raise NotImplementedError( NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None (cake) PS D:\Cake Eccomerce\cake\Cake_Bakery>
解决方案
错误根源是 Djongo 1.3.6 的代码中直接对 self.connection 做布尔判断,但 MongoDB 7.0.3 配套的 pymongo 版本已不再允许对 Database 对象进行布尔值测试,必须显式与 None 比较。修复步骤如下:
- 找到虚拟环境中 Djongo 的
base.py文件,路径示例:D:\Cake Eccomerce\cake\Lib\site-packages\djongo\base.py - 打开文件定位到第 208 行的代码:
if self.connection: - 将该行修改为:
if self.connection is not None: - 保存文件后重新执行
python manage.py makemigrations
额外提示
控制台同时抛出了 URL 路由警告,建议同步修复 urls.py 中的路由规则:将以 / 开头的路由(如 '/products')改为不带开头斜杠的形式(如 'products'),避免后续路由匹配异常。
内容的提问来源于stack exchange,提问作者user19000614
相关产品推荐
相关产品推荐

