Slice on Django Model Queryset

11,305

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.

Share:
11,305
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    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 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

  • Admin
    Admin almost 8 years
    If result = Model.objects.all()[a: a+101] and then slice on result sliced = result[a: a+100] or use len() len(result), will Django make two queries?
  • Compadre
    Compadre almost 8 years