【问题标题】:django sort dict after query查询后的django排序字典
【发布时间】:2016-05-23 21:24:08
【问题描述】:

有一个包含网站的表格和一个带有描述的多对一表格 尝试获取列表,首先获取最新的描述,然后按描述的内容排序显示它们...

views.py 中有以下内容

def category(request, category_name_slug):
    """Category Page"""
    context_dict = {}

    try:
        category = Category.objects.get(slug=category_name_slug)
        subcategory = SubCategory.objects.filter(category=category)
        websites = Website.objects.filter(sub_categories=subcategory,     online=True, banned=False)
        sites = websites
        descriptions =     WebsiteDescription.objects.prefetch_related("about")
        descriptions = descriptions.filter(about__in=sites)
        descriptions = descriptions.order_by('about', '-updated')
        descs = []
        last_site = "" # The latest site selected
        # Select the first (the latest) from each site group
        for desc in descriptions:
            if last_site != desc.about.id:
                last_site = desc.about.id
                desc.url = desc.about.url
                desc.hs_id = desc.about.id
                desc.banned = desc.about.banned
                desc.referral = desc.about.referral
                descs.append(desc)
        context_dict['descs'] = descs
        context_dict['websites'] = websites
        context_dict['subcategory'] = subcategory
        context_dict['category'] = category
    except SubCategory.DoesNotExist:
        pass

    return render(request, 'category.html', context_dict)

这给了我一个包含网站及其最新描述的列表,所以我在 category.html 中有以下内容

        {% if category %}
        <h1>{{ category.name }}</h1>

{% for subcategory in category.subcategory_set.all %}

             <a href="/links/{{ category.slug }}/{{ subcategory.slug     }}">{{ subcategory.name }}  ({{ subcategory.website_set.all|length }}) </a>

        {% endfor %}

            {% if descs %}
{% load endless %}

{% paginate descs %}
                {% for desc in     descs|dictsortreversed:"description"|dictsortreversed:"officialInfo" %}

                        <ul id='list' class='linksteps'>

        <a href="/{{ desc.about_id }}" rel="nofollow" target="_blank">
        <img src="/static/screenshots/{{ desc.about_id }}.png" />
        </a>

                <li><h3><a href="/{{ desc.about_id }}" rel="nofollow"     target="_blank">{{ desc.about_id }}</a>{% if desc.title %} - {{ desc.title }}     {% endif %}</h3>


          {% if desc.description %}<b>Description: </b>{{     desc.description }}
          <br />{% endif %} {% if desc.subject %}<b>Keywords: </b>{{     desc.subject }}
          <br />{% endif %} {% if desc.type %}<b>Type: </b>{{ desc.type }}
          <br />{% endif %} {% if desc.officialInfo %} {% if     desc.language %}<b>Language: </b>{{ desc.language }}
          <br />{% endif %} {% if desc.contactInformation %}<b>Contact     info: </b>{{ desc.contactInformation }}
          <br />{% endif %}


          {% else %}
          {% endif %}
        </li>


                       </ul>
</div>

                {% endfor %}
 {% show_pages %}
            {% else %}
                <strong>No websites currently in category.</strong>
            {% endif %}
        {% else %}
            The specified subcategory {{ category_name }} does not exist!
        {% endif %}

一开始我用的是 dictsort

{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo"|dictsortreversed:"referral" %}

按所需顺序给我列表,所以我很高兴;) 然后我决定我需要一些分页,因为列表变得太长了。 django-endless-pagination 工作正常,也能做到它应该做的,但是它在 dictsort 启动之前拆分了我的列表。

有没有办法在分页发生之前和我在初始查询中order_by之后进行排序以选择最新的描述?

非常感谢

编辑:

没有得到任何答案,所以我的问题可能不清楚。

据我了解,我需要在 views.py 中对 context_dict 中的值进行排序,替换模板中的 dictsort

已解决:::

这样做对我来说是替换 dictsort 的诀窍。

descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1

【问题讨论】:

  • 您应该在视图中对数据进行排序,而不是在模板中。它不仅可以进行分页,而且速度也更快。
  • 在我最初尝试之后,我已经对结果感到满意,我的 django-fu 根本不够好,dictsort 给出了一个快速的结果,无法得到我在初始之后重新订购的部分在视图中排序
  • @MarkChackerian ,所以问题是如何在视图中对其进行排序?我能找到的最接近的方法是使用诸如 OrderedDict 之类的东西,但是我似乎无法获得正确的值,如果这是要走的路的话
  • 我不确定你到底是如何排序的,但如果可能的话,通常最好在数据库中进行排序——这样可以更好地控制分页,如果数据库索引正确。您可以对连接的模型进行排序——参见docs.djangoproject.com/en/1.9/ref/models/querysets/#order-by 中的示例另外,这里有一些一般提示stackoverflow.com/questions/2412770/…
  • 是的,order_by 是我通常这样做的方式,但除非我在这里非常错误并且也在问题中进行了解释,否则问题是我首先按日期排序以从描述中获取最新信息在多对多领域....也尝试了ordered = sorted,但请记住,它不起作用,但会再试一次。

标签: python django django-endless-pagination


【解决方案1】:

已解决:::

这样做对我来说是替换 dictsort 的诀窍。

descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1

【讨论】:

    猜你喜欢
    • 2019-08-14
    • 1970-01-01
    • 2014-06-14
    • 2020-07-16
    • 2020-08-16
    • 2015-10-26
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多