如何限制Django应用程序中显示的项目数

问题描述 投票:1回答:1

我的报纸应用程序中有这个Django模型:

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('article_detail', args=[str(self.id)])

它目前显示所有文章,但我想限制显示在3篇最新文章中的内容。怎么做的?

这是我的看法:

class ArticleListView(LoginRequiredMixin, ListView):
    model = Article
    template_name = 'article_list.html'
    login_url = 'login'

这是html模板:

{% extends 'base.html' %}

{% block title %}Articles{% endblock title %}

{% block content %}
  {% for article in object_list %}
    <div class="card">
      <div class="card-header">
        <span class="font-weight-bold">{{ article.title }}</span> &middot;
        <span class="text-muted">by {{ article.author }} | {{ article.date }}</span>
      </div>
      <div class="card-body">
        <p>{{ article.body }}</p>
        <a href="{% url 'article_edit' article.pk %}">Edit</a>
        <a href="{% url 'article_delete' article.pk %}">Delete</a>
      </div>
      <div class="card-footer">
        {% for comment in article.comments.all %}
          <p>
            <span class="font-weight-bold">{{ comment.author }} &middot;</span>
            {{ comment }}
          </p>
        {% endfor %}
      </div>
    </div>
<br />
  {% endfor %} 
{% endblock content %}
python django django-models
1个回答
3
投票

在你的(假设)ListView你应该定义queryset,类似于

class ArticleListView(LoginRequiredMixin, ListView):
        model = Article
        template_name = 'article_list.html'
        login_url = 'login'
        queryset = Article.objects.order_by('-date')[:3]

More on this here

© www.soinside.com 2019 - 2024. All rights reserved.