Providing a LIMIT param in Django query without taking a slice of a QuerySet

廉价感情. 提交于 2019-12-11 04:45:23

问题


I have a utility function in my program for searching for entities. It takes a max_count parameter. It returns a QuerySet.

I would like this function to limit the max number of entries. The standard way would be to take a slice out of my QuerySet:

return results[:max_count]

My problem is that the views which utilize this function sort in various ways by using .order_by(). This causes exceptions as re-ordering is not allowed after taking a slice.

Is it possible to force a "LIMIT 1000" into my SQL query without taking a slice?


回答1:


Do results[:max_count] in a view, after .order_by(). Don't be afraid of requesting too much from DB, query won't be evaluated until the slice (and even after it either).




回答2:


You could subclass QuerySet to achieve this, by simply ignore every slice and do [:max_count] at last in __getitem__, but I don't think it worths with the complex and side-effects.

If you are worrying about memory consumption by large queryset, follow http://www.mellowmorning.com/2010/03/03/django-query-set-iterator-for-really-large-querysets/

For normal usage, please just follow DrTyrsa's suggestion. You could write shortcuts to shorten the order_by and afterwards slice in code to simplify your code.



来源:https://stackoverflow.com/questions/9836659/providing-a-limit-param-in-django-query-without-taking-a-slice-of-a-queryset

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