我是新的Django,我一直在关注创建博客的教程。
我创建了一个显示帖子的博客。但是,它会按顺序显示帖子:最早的帖子,最新的帖子。
这是“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()
如何首先显示新帖子,旧帖子可以显示?
答案 0 :(得分:2)
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
或在创建查询集时执行此操作
Blog.objects.all().order_by('-date')
https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
答案 1 :(得分:1)
def blog(request):
post_list = Post.objects.all().order_by('-timestamp')
context = {
'post_list': post_list,
}
return render(request, 'blog/blog.html', context)