从嵌套重组的queryset中删除项目

时间:2011-04-15 12:15:00

标签: python django orm

我一直致力于一个将性能作为首要任务的项目,因此我尝试在每个页面使用单个查询来收集所有需要的信息。

任何人,我到了一个点,我有一个查询集需要根据列(左,右,中心)重新分组,然后再根据标题重新分组。逻辑工作正常,但是当第二个重组开始时它会占用整个查询集,同时我只需重新组合左侧或中心的项目。等等。所以,我搜索了从查询集中删除项目的函数,而没有访问数据库,只有我能找到的是构建一个自定义模板,这是我被卡住的地方:)

这是我的查询结果

    +------------+-------------------+------------+-----------+----+-----------+-----------+---------+----+-------------+-------------+
| col_mapper | list_title        | main_title | list_slug | id | slug      | is_active | site_id | id | domain      | name        |
+------------+-------------------+------------+-----------+----+-----------+-----------+---------+----+-------------+-------------+
| L          | gadget            | for sale   | gadget    |  2 | for-sale  |         1 |       1 |  1 | example.com | example.com |
| L          | furniture         | for sale   | frnture   |  2 | for-sale  |         1 |       1 |  1 | example.com | example.com |
| L          | engines           | for sale   | engines   |  2 | for-sale  |         1 |       1 |  1 | example.com | example.com |
| L          | women seeking men | personals  | wsm       |  1 | personals |         1 |       1 |  1 | example.com | example.com |
| L          | missed connection | personals  | misd-conn |  1 | personals |         1 |       1 |  1 | example.com | example.com |
| L          | men seeking women | personals  | msw       |  1 | personals |         1 |       1 |  1 | example.com | example.com |
| R          | massage           | services   | massage   |  3 | srvces    |         1 |       1 |  1 | example.com | example.com |
| R          | computers         | services   | compters  |  3 | srvces    |         1 |       1 |  1 | example.com | example.com |
+------------+-------------------+------------+-----------+----+-----------+-----------+---------+----+-------------+-------------+

在我的模板中,我做了类似的事情

            {% regroup dict by col_mapper as column_gr %}

        {% for column in column_gr %}                
            {{ column.grouper }}<br>

            {% regroup column.list by main_title as item_gr %}
                {% for i in item_gr %}
                    {{ i }}
                {% endfor %}
        {% endfor %}

第一个重新组合工作正常,但是一旦它进入第二个重组,它再次重新组合整个查询集,而我只想重新组合col_mapper等于col_mapper.grouper的位置。我尝试构建自定义标记,但大多数我知道的方法会导致查询集再次访问数据库进行过滤。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我没有对此进行测试,但您可以尝试:

{% regroup dict by col_mapper as column_gr %}

{% for column in column_gr %}                
    {{ column.grouper }}<br>
    {# assign the grouper to another variable #}
    {% with column.grouper as grouper %}
        {% regroup grouper by main_title as item_gr %}
        {% for i in item_gr %}
            {{ i }}
        {% endfor %}
    {% endwith %}
{% endfor %}