1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoのListViewで投稿データを逆順にソートする

Posted at

環境

・Python:3.8.5
・Django:3.1.2
・仮想環境:venv
・エディタ:Pycharm

やること

・投稿ができる掲示板アプリで投稿を逆順にしたい

事前準備

models.py の投稿クラスに作成日時である created_at (名前はなんでもいいけど)を追加します。

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

・汎用ビューの ListView をインポートし、PostListView クラスに継承する。
ordering で先ほど作成したモデルの created_at の逆順をかく。

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'

できたはず

自分はこれでできました。
もしうまく反映されていないようでしたらmigrationかけてみるかコードの間違いがないかを再確認してみてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?