Only show the latest 3 posts in Django?

廉价感情. 提交于 2019-12-06 11:49:13

问题


I've got a blog app in Django. I want to show the latest 3 blog posts on another page but can only show all of the blog posts ordered by date.

How can I show the latest 3 posts?

Do I filter this in the views or on the template tags?

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 %}

回答1:


Try this,

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



回答2:


Try to get subarray of first 3 elements. It should work.

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


来源:https://stackoverflow.com/questions/23928866/only-show-the-latest-3-posts-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!