Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i show recent posts first in Django blog?

Tags:

date

django

blogs

I'm new Django, and i've been following a tutorial on creating a blog.

I've created a blog, that displays the posts. But, it displays the posts in the order: oldest posts first, and newest posts last.

This is the code in "models.py":

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

How can i display the new posts first and the old posts last?

like image 969
Adnan Avatar asked Dec 20 '25 05:12

Adnan


1 Answers

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

    class Meta:
        ordering = ['-date',]

https://docs.djangoproject.com/en/dev/topics/db/models/#meta-options

or do it with when you create the queryset

Blog.objects.all().order_by('-date')

https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

like image 57
Timmy O'Mahony Avatar answered Dec 24 '25 11:12

Timmy O'Mahony