嗯,我不确定这是否是最好的答案,但由于这个问题到目前为止没有回复,我将发布我最终用于后代的解决方案:
我创建了一个辅助函数,在关闭连接之前检查我们当前是否处于原子块中:
import django
from django.db import connection
from my_app import models
def close_connection():
"""Closes the connection if we are not in an atomic block.
The connection should never be closed if we are in an atomic block, as
happens when running tests as part of a django TestCase. Otherwise, closing
the connection is important to avoid a connection time out after long actions.
Django does not automatically refresh a connection which has been closed
due to idleness (this normally happens in the request start/finish part
of a webapp's lifecycle, which this process does not have), so we must
do it ourselves if the connection goes idle due to stuff taking a really
long time.
"""
if not connection.in_atomic_block:
connection.close()
def my_process():
django.setup()
while (True):
do_stuff()
close_connection()
models.MyDjangoModel().save()
正如评论所述,close_connection阻止了connection.close在测试中被调用,因此我们不再破坏测试事务。