【发布时间】:2021-07-16 07:34:00
【问题描述】:
我需要限制 Django 查询中的帖子数量。我试图添加一个最小值和最大值,但似乎没有任何效果。我已将 home.html 添加到代码中。
示例:我的博客中应该只有 15 篇最近的帖子。其余的可以通过点击类别按钮查看。
主页.html:
{% extends 'base.html' %}
{% block content %}
<h1>Posts</h1>
<ul>
{% for post in object_list %}
<li><a href="{% url 'article-detail' post.pk %}">{{post.title}}</a>
<style>
a {
text-transform: capitalize;
}
</style>
- <a href="{% url 'category' post.category %}">{{ post.category }}</a> - <a href="{% url 'show_profile_page' post.author.profile.id %}">{{ post.author.first_name }}
{{ post.author.last_name }}</a> - {{ post.post_date }} <small>
{% if user.is_authenticated %}
{% if user.id == post.author.id %}
- <a href="{% url 'update_post' post.pk %}">(Edit)</a>
<a href="{% url 'delete_post' post.pk %}">(Delete)</a>
{% elif user.id == 1 %}
- <a href="{% url 'update_post' post.pk %}">(Edit)</a>
<a href="{% url 'delete_post' post.pk %}">(Delete)</a>
{% endif %}
{% endif %}
</small><br/>
{{ post.snippet }}</li>
{% endfor %}
</ul>
{% endblock %}
view.py:
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-id']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args,**kwargs)
context["cat_menu"] = cat_menu
return context
models.py:
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to='images/')
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='intro')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='post_likes')
dislikes = models.ManyToManyField(User, related_name='post_dislikes')
【问题讨论】:
-
@ToniSredanović 不,我的意思是我的博客中应该只有 15 个最近的帖子。其余的可以通过点击类别按钮查看。
-
只需在您的初始模板中添加此查询集:
Post.objects.filter(<how_you_want_to_filter>).order_by('-<order_based_on_some_date>')[:15] -
类似的东西。但是我不需要在我的views.py中添加它也将它作为答案发布,以便未来的读者轻松找到答案。 @bdbd
-
是的,您需要将其添加到您的主视图中的某个位置。也许在
get_context_data中,类似于recent_posts?