Alex Kondrashov
Alex Kondrashov

Reputation: 61

Django: how to get the second last object from database?

I have a model for news. I add news to the database with Django admin. Model Post consists of title, body and image.

On the main.html page of my project i have a carousel with 3 slides. I already have some news in my database, and I want to display the last, the second last and so on images in that carousel.

My question is: what code should I add in html to display the last, the second last and the third last images?

<img src="???"> {# the last image #}
<img src="???"> {# the second last image #}
<img src="???"> {# the third last image #}

Upvotes: 1

Views: 2093

Answers (2)

Nikita Tonkoskur
Nikita Tonkoskur

Reputation: 1499

# views.py
from django.views.generic import TemplateView
class HomePageView(TemplateView):
    template_name = 'home.html'
    posts = Post.objects.all().order_by('-id') 

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context = {
            'carousel_posts': self.posts[:3],
        }
        return context

Use this make a for loop over the carouser_posts keyword in your template and extract the information you need.

<div class="carousel-inner">
  {% for post in carousel_posts %}
      <div class="carousel-item active">
        <img src="{{post.image}}">
        <p>{{post.title}}"</p>
      </div>
    {% endfor %}
 </div>

UPDATE Answer to your update. Using context keyword carousel_posts provided by our HomePageView we can access post objects one by one using for loop.

In template, assuming that your Post model has an image field called image.

{% for post in carousel_posts %}
    <img src="{{ post.image.url }}"> 
{% endfor %}

Upvotes: 0

ruddra
ruddra

Reputation: 52028

You can try like this:

posts= Post.objects.all().order_by('-id')
last_post = posts[0]
second_last_post = posts[1]
third_last_post = posts[2]
last_three_posts = posts[0:3]

But make sure to have atleast three posts or else it will throw index error

Upvotes: 2

Related Questions