You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django测试数据库创建失败:无vector扩展创建权限

Django测试数据库权限与创建异常解决方案

问题背景

执行poetry run python manage.py test minigames.test.models时出现以下问题:

  1. 终端提示Python版本不兼容,自动切换至3.13.3
  2. 检测到测试数据库test_aivector_db已存在,确认删除后触发权限错误:permission denied to create extension "vector",提示需超级用户权限
  3. 生产数据库已分配超级用户权限且vector扩展已创建,但Django测试会单独生成测试库,切换端口无法解决
  4. 当前数据库配置:
DATABASE_URL=postgres://minidb:postgres@localhost:5432/aivector_db

---
# settings.py database settings
DATABASES = {
    'default': dj_database_url.config(conn_health_checks=True, engine='dj_db_conn_pool.backends.postgresql'),
}

解决方案

1. 彻底清理残留测试数据库

  • 用PostgreSQL超级用户登录psql:psql -U postgres
  • 列出所有数据库确认残留:\l
  • 强制删除测试库(即使有连接):DROP DATABASE IF EXISTS test_aivector_db WITH FORCE;
  • 退出psql:\q

2. 给测试用户分配扩展创建权限

Django测试使用生产库的minidb用户,需给该用户授权创建vector扩展的权限:

  • 登录psql超级用户:psql -U postgres
  • 授权用户在public schema创建对象:GRANT CREATE ON SCHEMA public TO minidb;
  • 切换到模板库template1:\c template1,添加vector扩展(新测试库会自动继承):CREATE EXTENSION IF NOT EXISTS vector;
  • 退出psql:\q

3. 配置Django测试专属数据库

在settings.py中单独配置测试数据库,使用超级用户执行测试:

DATABASES = {
    'default': dj_database_url.config(conn_health_checks=True, engine='dj_db_conn_pool.backends.postgresql'),
    'test': {
        'ENGINE': 'dj_db_conn_pool.backends.postgresql',
        'NAME': 'test_aivector_db',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

或者通过测试信号自动创建扩展:

from django.db.models.signals import post_migrate
from django.dispatch import receiver

@receiver(post_migrate)
def setup_vector_extension(sender, **kwargs):
    if kwargs.get('using') == 'test' and sender.name.startswith('minigames'):
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("CREATE EXTENSION IF NOT EXISTS vector;")

4. 锁定Poetry环境的Python版本

  • 修改pyproject.toml,指定项目兼容的Python版本,例如:python = "^3.10"
  • 切换到指定版本的Poetry环境:poetry env use 3.10(替换为实际兼容版本)
  • 重新安装依赖:poetry install

内容的提问来源于stack exchange,提问作者khanzala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 04:37:14