我制作了我的帖子模型,我存储了所有帖子信息,比如标题,正文,标签等等。我用for循环将它链接到我的索引模板:
<!-- Blog Post -->
{% for blog in object_list %}
<div class="card mb-4">
<div class="card-body">
<h4 id="post_title" class="card-title">{{blog.title}}</h2>
<div id="post_body" class="card-text">{{blog.formatted_markdown|safe}}</div>
<a href="details/{{blog.id}}" class="btn btn-primary">Read More</a>
</div>
<div class="card-footer text-muted">
<p id="foot_page">{{blog.date}}</p>
<a id="foot_page" href="#">{{blog.author}}</a>
</div>
</div>
{% endfor %}
当我运行我的服务器时,帖子会出现在pub_date升序排序的博客上,所以新的帖子会显示为旧的。
如何让最新的帖子显示在最上面?
这是我的Post模型课,如果有用的话:
class Post(models.Model):
title = models.CharField(max_length=255)
body = MarkdownxField()
tags = models.ManyToManyField(Tag)
author = models.CharField(max_length=255, default='Raúl Chirinos')
date = models.DateTimeField(auto_now_add=True, blank=True)
@property
def formatted_markdown(self):
return markdownify(self.body)
def __str__(self):
return self.title
我在urls文件中管理了视图:
from django.conf.urls import url
from django.urls import include, path
from django.contrib import admin
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from raulchirinos.models import Post
app_name = 'raulchirinos'
urlpatterns = [
url(r'^markdownx/', include('markdownx.urls')),
url(r'^admin/', admin.site.urls, name='admin-site'),
url(r'^$', ListView.as_view(model=Post, template_name='raulchirinos/index.html'), name='index'),
url(r'^details/(?P<pk>[0-9]+)/$', DetailView.as_view(model=Post, template_name='raulchirinos/post_template/post.html'), name='post_details'),
]
答案 0 :(得分:0)
向模型添加元类,并根据您的要求设置排序。
例如:
class Post(models.Model):
title = models.CharField(max_length=255)
body = MarkdownxField()
tags = models.ManyToManyField(Tag)
author = models.CharField(max_length=255, default='Raúl Chirinos')
date = models.DateTimeField(auto_now_add=True, blank=True)
class Meta:
ordering = ['-date']
@property
def formatted_markdown(self):
return markdownify(self.body)
def __str__(self):
return self.title
答案 1 :(得分:0)
根据您需要订购的级别,您有多种选择:
ordering
属性设置为按date
降序排序。请参阅:https://docs.djangoproject.com/en/2.0/ref/models/options/#ordering class Post(models.Model):
# ...
class Meta:
ordering = ["-date"]
当然,最好的选择可能是第一个,因为在你检索多个帖子时,你可能想要这个排序。