为什么Django模型在线程池中返回一个空的QuerySet?
我在API中使用了ThreadPoolExecutor。在测试案例中,我生成了一个电影实例,并将其保存在数据库(PostgreSQL)中。我在测试用例,API和线程池功能中打印了电影计数。为什么在线程池中返回一个空的QuerySet?
view.py:
def movie_count():
print(Movie.objects.count(), "movie count in the thread")
class MovieListView(APIView):
renderer_classes = (
render.CamelCaseJSONRenderer,
renderers.BrowsableAPIRenderer,
)
def get(self, request, key, format=None):
print(Movie.objects.count(), "movie count before the thread")
with ThreadPoolExecutor(1) as executor:
bookmarked_future = executor.submit(movie_count)
bookmarked_future.result()
return Response({})
test.py
def test_mock_function(self):
Movie.objects.create(
title="Title"
)
print(Movie.objects.count(), "movie count in the test")
url = reverse('video_api:list', args=('tops',))
self.client.get(url, format='json', data={'limit': 30})
结果:
1 movie counts in the test
1 movie count before the thread
0 movie count in the thread
I used ThreadPoolExecutor in my API. in the test case, I generated a Movie instance and saved it in the database (PostgreSQL). I printed movie count in the test case, API, and thread pool function. why in the thread pool return an empty queryset?
view.py:
def movie_count():
print(Movie.objects.count(), "movie count in the thread")
class MovieListView(APIView):
renderer_classes = (
render.CamelCaseJSONRenderer,
renderers.BrowsableAPIRenderer,
)
def get(self, request, key, format=None):
print(Movie.objects.count(), "movie count before the thread")
with ThreadPoolExecutor(1) as executor:
bookmarked_future = executor.submit(movie_count)
bookmarked_future.result()
return Response({})
test.py
def test_mock_function(self):
Movie.objects.create(
title="Title"
)
print(Movie.objects.count(), "movie count in the test")
url = reverse('video_api:list', args=('tops',))
self.client.get(url, format='json', data={'limit': 30})
result:
1 movie counts in the test
1 movie count before the thread
0 movie count in the thread
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了答案。
DJANGO测试中的testcase and TrassActionTestCase之间的差异
I found the answer.
Difference between TestCase and TransactionTestCase classes in django test