【问题标题】:Django - sort related items, in a template, by a number of filtered foreign key objectsDjango - 在模板中通过一些过滤的外键对象对相关项目进行排序
【发布时间】:2015-09-10 02:50:28
【问题描述】:

假设我有一个包含嵌套类别的博客。

我是这样显示它们的:

{% for category in categories %}
   <h1> {{category.title}} </h1>
   {% for subcategory in category.subcategories %}
      <h1> {{subcategory.title}} </h1>
   {% endfor %}
{% endfor %}

我需要按已发布帖子的数量对类别及其子类别进行排序。

我该怎么做?


也许我可以在模型的 Meta 类中使用排序,但我不知道是否可以通过一些过滤的外键进行排序。我也不想在模型中这样做,因为我不想总是按那个顺序对它们进行排序。

或者我可以写一些模板标签来对相关项目进行排序,看起来很方便,但我不知道怎么做。

或者也许还有其他更好的方法?


更新:

我创建了一个按帖子数量对类别进行排序的过滤器:

@register.filter
def sortbyposts(categories):
    categories = categories.annotate(number_of_posts=Count('posts')).order_by('-number_of_posts')
    return categories

我可以这样使用它:

{% for category in categories|sortbyposts %}
   <h1> {{category.title}} </h1>
   {% for subcategory in category.subcategories|sortbyposts %}
      <h1> {{subcategory.title}} </h1>
   {% endfor %}
{% endfor %}

但现在我需要通过过滤后的帖子来计数()。我可以这样做吗?

【问题讨论】:

  • 为什么不在视图中对categories 进行排序,然后再将其传递给模板上下文?
  • 因为 category.subcategories 返回未排序的子类别。

标签: django django-templates


【解决方案1】:

我的解决方案:

创建模板标签:

@register.filter
def sortbypostcount(children):
    children_postcount = []
    for child in children:
        child.postcount = child.posts.filter(published=True,rational=False).count()
        children_postcount.append(child)

    children_postcount.sort(key=lambda x: x.postcount, reverse = True)

    return children_postcount

使用它对结果进行排序:

{% for category in categories|sortbypostcount %}
   <h1> {{category.title}} </h1>
   {% for subcategory in category.subcategories|sortbypostcount %}
      <h1> {{subcategory.title}} </h1>
   {% endfor %}
{% endfor %}

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 2021-11-17
    • 2018-08-14
    • 2018-10-05
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多