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

如何在pytest测试函数中确定当前使用的Django数据库?

在pytest Django测试中获取当前运行的数据库

当然可以,以下是两种实用的实现方式:

方法1:操作特定数据库时显式记录别名

如果你的测试需要同时操作两个数据库,可在切换数据库上下文时直接记录当前使用的别名,示例代码:

import pytest
from django.db import transaction
from myapp.models import MyModel

pytestmark = pytest.mark.django_db(databases=["db1", "db2"])

def test_case_1():
    # 操作db1
    with transaction.atomic(using="db1"):
        current_db = "db1"
        print(f"当前操作的数据库: {current_db}")
        # 执行db1相关操作
        obj_count = MyModel.objects.using("db1").count()
        print(f"{current_db}中MyModel实例数量: {obj_count}")
    
    # 操作db2
    with transaction.atomic(using="db2"):
        current_db = "db2"
        print(f"当前操作的数据库: {current_db}")
        # 执行db2相关操作
        obj_count = MyModel.objects.using("db2").count()
        print(f"{current_db}中MyModel实例数量: {obj_count}")

方法2:参数化fixture分别测试每个数据库

如果需要让测试用例针对每个数据库单独运行一次,可通过参数化fixture传递数据库别名,示例代码:

import pytest
from django.db import connections
from myapp.models import MyModel

@pytest.fixture(params=["db1", "db2"])
def current_db(request):
    return request.param

pytestmark = pytest.mark.django_db(databases=["db1", "db2"])

def test_case_1(current_db):
    print(f"当前运行测试的数据库: {current_db}")
    # 使用当前数据库别名执行操作
    obj_count = MyModel.objects.using(current_db).count()
    print(f"{current_db}中MyModel实例数量: {obj_count}")
    
    # 直接操作数据库连接
    with connections[current_db].cursor() as cursor:
        cursor.execute("SELECT VERSION()")
        db_version = cursor.fetchone()[0]
        print(f"{current_db}版本: {db_version}")

说明:Django本身不会自动维护"当前全局数据库"的状态,所有跨数据库操作都需要显式指定别名。上述两种方法分别对应"同时操作多库"和"分库单独测试"的场景,可根据你的需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:17:11