Sort post data in reverse order with Django's ListView

environment

-Python: 3.8.5 ・ Django: 3.1.2 ・ Virtual environment: venv ・ Editor: Pycharm

things to do

・ I want to reverse the order of postings with a bulletin board application that allows posting.

Advance preparation

-Add the creation date and time created_at (whatever the name is) to the post class of models.py.

models.py



from django.utils import timezone


class Post(models.Model):
    title = models.CharField(max_length=20)
    content = models.CharField(max_length=140)
    created_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

View

-Import the generic view ListView and inherit it to the PostListView class. -Write the reverse order of created_at of the model created earlier with ʻordering`.

views.py



from django.views.generic import ListView
from .models import Post


class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    ordering = ['-created_at']
    template_name = 'index.html'

Should have been done

I was able to do this. If it doesn't seem to be reflected well, try migration or double check for code mistakes.

Recommended Posts

Sort post data in reverse order with Django's ListView
Get additional data in LDAP with python
Try working with binary data in Python
Post Test 3 (Working with PosgreSQL in Python)
Overwrite data in RDS with AWS Glue
Working with 3D data structures in pandas
Visualize corona infection data in Tokyo with matplotlib
Generate and post dummy image data with Django
Delete data in a pattern with Redis Cluster
Read table data in PDF file with Python
I struggled with conditional branching in Django's Templates.
Sort dict in dict (dictionary in dictionary) with a specific key
Sort list elements in a specified order in Python
Iterative (recursive) processing with tkinter (displayed in order)