【问题标题】:Adding a maximum limit to the number of post using python使用python为帖子数量添加最大限制
【发布时间】: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(&lt;how_you_want_to_filter&gt;).order_by('-&lt;order_based_on_some_date&gt;')[:15]
  • 类似的东西。但是我不需要在我的views.py中添加它也将它作为答案发布,以便未来的读者轻松找到答案。 @bdbd
  • 是的,您需要将其添加到您的主视图中的某个位置。也许在get_context_data 中,类似于recent_posts

标签: python django


【解决方案1】:

我认为当您单击类别按钮时,您还有另一个用于显示分类对象的模板。正如你所说的

“我的博客中应该只有 15 个最近的帖子。其余的可以 点击类别按钮即可看到。”

在这种情况下,您可以使用一个简单的技巧来显示您表格中的最新帖子。 在views中按降序查询所有对象

    all_objs = Post.objects.all().order_by('-id')

然后使用{% if forloop.counter &lt;= 15 %} 仅显示最后 15 项。如下。

模板

{% for post in object_list %}

   {% if forloop.counter <= 15 %}

       <h4>{{obj}} #or anything really that is meant to be shown on the home page.</h4>

   {% endif %}

{% endfor %}

【讨论】:

  • 我一定会在 10 分钟内告诉你结果谢谢。
  • 我也建议进行编辑,请同行评审。
  • 是的。我尽量保持简单。在查询之前我不明白ordering = ('-id') 这一行。这是干什么用的。
  • 好酷。我无法理解你在你的问题中的意思。你能解释一下吗?你的意思是from django import template这个导入还是别的什么
  • 我将在此处发布问题的链接......如果你没问题。
【解决方案2】:

https://docs.djangoproject.com/en/3.2/topics/pagination/

最好的方法是 Django Pagintion。

{% for contact in page_obj %}
    {# Each "contact" is a Contact model object. #}
    {{ contact.full_name|upper }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
from django.core.paginator import Paginator
from django.shortcuts import render

from myapp.models import Contact

def listing(request):
    contact_list = Contact.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page.

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'list.html', {'page_obj': page_obj})

【讨论】:

  • 这也很有帮助,我以后甚至可能会使用它。
【解决方案3】:

你可以这样做:

def get_context_data(self, *args, **kwargs):
    context = super(HomeView, self).get_context_data(*args,**kwargs)
    context["cat_menu"] = Category.objects.all()
    context["most_recent_posts"] = Post.objects.filter(author=self.request.user).order_by('-post_date')[:15]
    return context  

这将获取当前用户最近撰写的 15 个帖子,按发布日期排序。

然后只需处理在home.html 中显示此内容,例如:

<ul>
{% for p in most_recent_posts %}
    <li>{{ p.title }}</li>
{% endfor %}
</ul>

【讨论】:

  • 对不起,我在views.py中错过了一个小bi。我认为您可能需要稍微调整一下代码。检查我编辑的帖子。
  • 是的,只需将其添加到您当前的。
  • 抱歉,这不起作用。我不确定为什么。我添加了您的 def func 并进行了一些调整,但遗憾的是它没有起作用。
  • 已更新以适用于您当前的实施。请注意,您还需要修改 home.html 才能实际使用这个新上下文。
  • 一个小问题,我是直接保留 ordering = [-id] 函数还是必须更改它。
【解决方案4】:

只需将查询限制为按post_date 排序的最新 15 个条目:

cat_menu = Category.objects.latest("post_date")[:15]

【讨论】:

    【解决方案5】:

    您可以使用 Django 分页 api 。通过页码管理您的数据。最初传递 1 并在分页给出的页码之后。

     paginator = Paginator(yourquerysetdata, 20)
            page_num = request.data.get('page')
            result = yourSerializerName(paginator.get_page(page_num) many=True).data
            try:
                page = paginator.page(page_num)
            except:
                page = paginator.page(1)
    
            count = paginator.num_pages
    
            resultobj = paginator.get_page(page_num)
            has_prev = resultobj.has_previous()
            has_next = resultobj.has_next()
            page_range = resultobj.paginator.page_range.stop - 1
            if has_prev:
                prev_page_no = resultobj.previous_page_number()
            else:
                prev_page_no = 0
    
            if has_next:
                next_page_no = resultobj.next_page_number()
            else:
                next_page_no = None
    
            context = dict()
            context['page'] = page.number
            context['page_no'] = count
    

    【讨论】:

    • 嗨,我喜欢你的想法,但我不想要单独的页面,而只是限制一页中的帖子数量。
    【解决方案6】:

    这很简单。您只需修改用于获取帖子的查询。
    get_context_data() 方法中,将cat_menu = Category.objects.all()
    替换为cat_menu = Category.objects.all().order_by('-post_date')[:15]。这会将结果的数量限制为 15 个最近的对象。 如需更多了解,您可以查看Limiting QuerySets 的官方 Django 文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多