我怎样才能在 Django 中显示最后 4 个帖子?

How can I show last 4 posts in django?

我尝试使用基于 Class 的视图在 Django 中显示最后 4 post 秒,但页面上未显示任何数据 (post)。 那是代码: views.py :

class PostList(ListView):
    model=Post
    paginate_by=10
    context_object_name='all_posts'
    ordering=['-created_at']
    latest=model.objects.order_by('-created_at')[:4]

templates/post_list.html :

{% for post in latest  %}
                <div class="col-sm-12 col-md-6 col-lg-3" >
                    <!-- cards-->
                    <div class="card ">
                        
                        <img src="{{post.image.url}}" class="card-img-top" alt="...">
                        <div class="card-body">
                        <h5 class="card-title">{{post.title}}</h5>
                        <p class="card-text">{{post.content}}</p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                        </div>
                    </div>

                    <!-- ends cards-->
                </div>
                {% endfor %} 

非常感谢

使用 get_aueryset() 来做到这一点!

这是 Django documentations

class PostList(ListView):
    template_name = "templates/post_list.html"
    model = Post
    ordering = ["-created_at"]
    context_object_name = "all_posts"

    def get_queryset(self):
        queryset = super().get_queryset()
        data = queryset[:4]
        return data