只显示Django最新的3个帖子?

时间:2014-05-29 08:22:05

标签: python django django-views

我在Django有一个博客应用程序。我想在另一个页面上显示最新的3篇博文,但只能显示按日期排序的所有博客文章。

如何显示最新的3个帖子?

我是在视图中还是在模板标签上过滤它?

models.py

from django.db import models
from django.core.urlresolvers import reverse

# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True, max_length=255, null=True)
    pub_date = models.DateTimeField()
    excerpt = models.TextField(null=True)
    text = models.TextField()
    header_image = models.FileField(upload_to='blog/%Y/%m/%d', null=True, blank=True)
    post_color = models.CharField(max_length=20, null=True)
    tags = models.CharField(max_length=80, blank=True)
    published = models.BooleanField(default=True)

    def __unicode__(self):
        return u'%s' % self.title

    def get_absolute_url(self):
        return reverse('blog.views.post', args=[self.slug])

views.py

from django.shortcuts import render, get_object_or_404
from blog.models import Post

def about(request):
        # get the blog posts that are published
        posts = Post.objects.filter(published=True).order_by('-pub_date')
        # now return the rendered template
        return render(request, 'blog/about.html', {'post': posts})

about.html

{% for post in post %}
        <section class="post">
                <h3><a class="post-title"
                    href="{{post.get_absolute_url}}">
                    {{ post.title }}
                </a></h3>
                <span class="post-meta">
                    {{ post.pub_date | date:"d F Y" }}
                </span>
                <p class="post-excerpt">
                    {{ post.excerpt }}
                </p>
        </section>
{% endfor %}

2 个答案:

答案 0 :(得分:5)

试试这个,

posts = Post.objects.filter(published=True).order_by('-pub_date')[0:3]

答案 1 :(得分:2)

尝试获得前3个元素的子数组。它应该工作。

posts = Post.objects.filter(published=True).order_by('-pub_date')[:3]