更新时间:2023-02-02 21:32:03
这是Django中的一个已知错误: https://code.djangoproject.com/ticket/23718
This is a known bug in Django: https://code.djangoproject.com/ticket/23718
该票中描述的解决方法是***的选择.我遇到了同样的问题,并通过定义自定义TestCase类并在所有测试中从该自定义测试用例继承来实现了变通方法.我还选择使用setUpClass和tearDownClass代替bug票证中所述的setUp和tearDown.无论哪种都可以.
The workaround described in that ticket is your best bet. I ran into this same issue and implemented the workaround by defining a custom TestCase class and inheriting from that custom test case in all my tests. I also chose to use setUpClass and tearDownClass instead of setUp and tearDown as described in the bug ticket. Either should work though.
from django.db import connections
class CustomTestCase(TestCase):
@classmethod
def setUpClass(cls):
super(CustomTestCase, cls).setUpClass()
connections['replica']._orig_cursor = connections['replica'].cursor
connections['replica'].cursor = connections['default'].cursor
@classmethod
def tearDownClass(cls):
connections['replica'].cursor = connections['replica']._orig_cursor
super(CustomTestCase, cls).tearDownClass()