Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice on Django Model Queryset

I try to run a query for paged results, like this Model.objects.all()[start: start+page_size].

I also want to know whether there are more pages to load, that is to say, I want to know whether start+page_size < Model.objects.all().count().

My question is, if I call all() twice here, whether Django executes the same query twice (one for slice operation[], one for count()).

Another question is if I slice on a Model.objects.all() like this Model.objects.all()[2:9] whether Django fetch all data from DB and slice by python, or Django only fetch with SQL limit limit 2 to 9

like image 532
Yanye Li Avatar asked Dec 24 '22 03:12

Yanye Li


1 Answers

Yes, it makes two queries, but these are not the "same query" at all. One is SELECT * FROM mymodel LIMIT <page_size> OFFSET <start> and the other is SELECT COUNT(*) FROM mymodel.

If you want to avoid two queries, a simple fix is to ask for one more record than you actually need:

Model.objects.all()[start: start+page_size+1]

then you can iterate up to page_size, and show the Next button if the extra record is there.

like image 130
Daniel Roseman Avatar answered Feb 15 '23 21:02

Daniel Roseman