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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With