如何显示 prefetch_related 生成的查询

How to display query generated by prefetch_related

我有一个带有 prefetch_related() 的查询集(带有 Prefetch 对象)

我想查看原始查询和 print(qs.query),它没有显示任何关于 prefetch_related 的内容。

如何查看由于 prefetch_related 而成为 运行 的查询?

查询集的 query 对象只会显示 Django 为查询集本身生成的查询(在应用任何 prefetch_related 等之前)。

您可能需要查看 these guidelines 以检查实际发送到您的数据库的查询:

from django.db import connection
print(connection.queries)

或者您可以使用 django-debug-toolbar 之类的东西来显示查询。