我的报纸应用程序中有这个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> ·
<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 }} ·</span>
{{ comment }}
</p>
{% endfor %}
</div>
</div>
<br />
{% endfor %}
{% endblock content %}
在你的(假设)ListView
你应该定义queryset
,类似于
class ArticleListView(LoginRequiredMixin, ListView):
model = Article
template_name = 'article_list.html'
login_url = 'login'
queryset = Article.objects.order_by('-date')[:3]