Django模板标签regroup的使用

发布时间 2023-03-22 22:03:17作者: super_ip

在使用 Django 开发时,有时候我们需要在模板中按对象的某个属性分组显示一系列数据。例如博客文章按照时间归档分组显示文章列表(示例效果请看我的博客的归档页面),或者需要按日期分组显示通知(例如知乎)的通知列表。如果不熟悉 Django 内置的 regroup 模板标签,要完成这个需求可能还得费点功夫,而使用 regroup 则可以轻松完成任务。

参考链接:https://cloud.tencent.com/developer/article/1099560

{% regroup post_list by created_time.year as year_post_group %}

<ul>
  {% for year in year_post_group %}
  <li>{{ year.grouper }} 年
    {% regroup year.list by created_time.month as month_post_group %}
    <ul>
      {% for month in month_post_group %}
      <li>{{ month.grouper }} 月
        <ul>
          {% for post in month.list %}
          <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
          </li>
          {% endfor %}
        </ul>
      </li>
      {% endfor %}
    </ul>
  </li>
  {% endfor %}
</ul>

views.py试图代码:

def archives(request):
    """文章列表"""
   # blog=blog.user
    data_dict = {}
    value = request.GET.get("q", "")
    if value:
        #data_dict["title__contains"]=value
        data_dict["__icontains"] = value
   #article_list=models.Article.objects.datetimes("create_time","month",order="DESC")
    #article_list=models.Article.objects.filter(**data_dict).order_by("-create_time")
    
    article_list=models.Article.objects.filter(Q(title__icontains=value)|Q(content__icontains=value)).order_by("-create_time")
        
    return render(request,"archives.html",{"article_list":article_list,"value":value})

实际HTML页面应用: