[Django]-Django templates show the latest data first

2👍

You can do this by setting ordering in Meta of your model:

To show in reverse order put minus - before field name.

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article_detail', args=[str(self.id)])

    class Meta:
        ordering = ['-date']

1👍

Override the get_context_data() method

class ArticleListView(LoginRequiredMixin, ListView):
    model = Article
    template_name = 'article_list.html'
    login_url = 'login'

    def get_context_data(self, *args, **kwargs):
        context_data = super().get_context_data(*args, **kwargs)
        if context_data['object_list']:
            context_data['object_list'] = context_data['object_list'].order_by('-date')
        return context_data
👤JPG

1👍

I think the simplest way of achieving this is to use ordering:

class ArticleListView(LoginRequiredMixin, ListView):
    model = Article
    template_name = 'article_list.html'
    login_url = 'login'
    ordering = ['-date']

I would recommend this approach beacuse in this way, the ordering is specific to that ListView, where if you change in models, it will be reflected everywhere(even in places where you don’t need ordering by -date)

👤ruddra

Leave a comment