How to get only first "N" elements from postgres through views in Django using jinja

Viewed 321

I am using Django and postgres.

My views.py looks like:

def home(request):
    title = Scrap.objects
    return render(request, 'index.html', {'headlines': headlines})

My index.html looks like:

 <div class="content"
    style="background:white; color: white; font-family: Verdana;font-weight: 5;text-align: center;">
    {% for headline in headlines.all reversed %}
        <a href="{{ headline.url }}" target="_blank" style="color:black; font-size: medium;" />{{ headline.headlines }}</a>
        <hr style="border-bottom: dotted 1px #000" />
    {% endfor %}
  </div>

With the above code I am getting all the rows from the databse. How can I get only "N" rows?

I have tried:

{% for headline in headlines.all[:5] reversed %}

but it throws an error.

Could not parse the remainder: '[:5]' from 'headlines.all[:5]'

2 Answers

seems like you got into the wrong tutorial. This answer is may not the exact answer you may looking for, but this will give you the idea

# views.py
def home(request):
    limit = 5
    queryset = MyModel.objects.all()[:limit]
    return render(request, 'index.html', {'queryset': queryset})

# index.html
{% for headline in queryset reversed %}
    {{ headline }}
{% endfor %}

If you want the latest (last N rows which are added to the database):

MyModel.objects.all().order_by('-id')[:10]
Related