-Python: 3.8.5 ・ Django: 3.1.2 ・ Virtual environment: venv ・ Editor: Pycharm
・ I want to reverse the order of postings with a bulletin board application that allows posting.
-Add the creation date and time created_at
(whatever the name is) to the post class of models.py
.
timezone
.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'
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