Best way to crop a set of Django queries without getting into the database more than once

I run a query to get the last 5 Newsitems. In my template, I want to display the first element in one place, then the remaining 4 further down the page.

In my template, I am doing something like this:

{% for n in news|slice:":1" %}
    {{ n.headline }}
{% endfor %}

... more HTML ...

{% for n in news|slice:"1:" %}
    {{ n.headline }}
{% endfor %}

When I look at the Debug toolbar, this leads to two queries in the database: one with LIMIT 1and the other with LIMIT 4 OFFSET 1, but the rest is the same. I appreciate that this is the way Django is wise to only request the material that you are actually using, but in this case it seems a little excessive. What is the best way to do this?

+5
source share
2 answers

. , len() , .

Django , . - , .

+5

, .

var = list(somequery[:5])
+9

All Articles