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

时间:2019-03-28 14:07:38

标签: python django django-models

我的报纸应用中有这个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 %}

1 个答案:

答案 0 :(得分: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