Slice on Django Model Queryset
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 04, 2022Comments
-
Admin about 2 years
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 forcount()
).Another question is if I slice on a
Model.objects.all()
like thisModel.objects.all()[2:9]
whether Django fetch all data from DB and slice by python, or Django only fetch with SQL limitlimit 2 to 9
-
Admin almost 8 yearsIf
result = Model.objects.all()[a: a+101]
and then slice on resultsliced = result[a: a+100]
or use len()len(result)
, will Django make two queries? -
Compadre almost 8 years