Django: How to calculate a set of queries and return a slice without double clicking on the database?

I have this piece of code in my API that has recently become a bit of a bottleneck:

total = results.count() if request.GET.has_key('offset'): offset = int(request.GET.get('offset').strip()) results = results.order_by('name')[100*offset:100*(offset+1)] people = list(results) 

Note that results are a set of queries for all people, and offset is a parameter used for pagination.

Here I see when I type connection.queries that my database is twice in the number of .count() and list(results) . The reason .count() should be at the top, because I need the length of all people (not 100.) Is there a way around this?

+5
source share
1 answer

Maybe something like this ?:

 allpeople = list(results.order_by('name')) total = len(allpeople) if request.GET.has_key('offset'): offset = int(request.GET.get('offset').strip()) results = allpeople[100*offset:100*(offset+1)] people = results 

Keep in mind that when people = results will crash if if request.GET....: does not work.

0
source

All Articles