django's .extra(where= clauses are clobbered by table-renaming .filter(foo__in=… subselects

浪子不回头ぞ 提交于 2019-12-03 17:08:05

At first: the issue is not totally clear to me. Is the second code block in your question the actual code you want to execute? If this is the case the query should work as expected since there is no subselect performed.

I assume so that you want to use the second code block without the list() around the subselect to prevent a second query being performed.


The django documentation refers to this issue in the documentation about the extra method. However its not very easy to overcome this issue.

The easiest but most "hakish" solution is to observe which table alias is produced by django for the table you want to query in the extra method. You can rely on the persistent naming of this alias as long as you construct the query always in the same fashion (you don't change the order of multiple extra methods or filter calls that cause a join).

You can inspect a query that will be execute in the DB queryset by using:

print Model.objects.filter(...).query

This will reveal the aliases that are used for the tables you want to query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!