Providing a LIMIT param in Django query without ta

2019-08-01 03:37发布

问题:

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.