Search code examples
djangodateblogs

How do i show recent posts first in Django blog?


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?


Solution

  • 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