使用字典的Django分页,其中键是列表 [英] Django pagination with dictionary where key is a list

查看:54
本文介绍了使用字典的Django分页,其中键是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 views.py 文件中有一个字典,其中的值是列表.在我的模板中,我有以下html:

I have a dictionary in my views.py file where the values are lists. In my template I have the following html:

{% for key, values in my_dict %}
    <tr>
        <td colspan="6" class="key">{{ key }}</td>
    </tr>
    {% for value in values %}
        <tr>
            <td colspan="6" class="value">{{ value }}</td>
        </tr>
    {% endfor %}
{% endfor %}

会打印出键的名称,后跟值中的列表项.但是,我希望能够对键进行分页,以便每页仅显示10个键及其值.

which prints out the name of the key followed by the list items inside the value. However, I want to be able to paginate the keys such that only 10 keys with their values appear per page.

我有以下代码在 views.py 中的 index 方法中进行分页:

I have the following code to do the pagination inside my index method in views.py:

paginator = Paginator(myDict, 10)
page_num = requests.GET.get('page', 1)
page = paginator.page(page_num)

我将模板更新为 {%键,页面%中的值} ,当然,我收到TypeError,因为它是可哈希的类型.我只是想知道如何才能产生与以前相同的结果,却不使用字典.

I updated my template to {% for key, values in page %} and of course I get a TypeError because it's a hashable type. I'm just wondering how I can go about producing the same results as before but without using a dictionary.

我找到了此答案,建议改用元组的字典,但这似乎对我不起作用,我猜是因为我的值是列表.

I found this answer that suggests using tuples instead of dictionaries, but that doesn't seem to work for me and I'm guessing because my values are lists.

推荐答案

我不确定是否可以算是一个好答案,但是无论如何:我只是想用 tuple 并且有效.因此,我认为问题可能出在您的代码中.我的测试代码:

I am not sure if it can be count as good answer but anyway: I have just tried to replicate your problem and solution with tuple and it worked. So I think the problem can be in your code. My test code:

>>> from django.core.paginator import Paginator
>>> d = {'a': [1,2], 'b': [3,4]}
>>> p = Paginator(d, 1)
>>> p1 = p.page(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type
>>> t = tuple(d.items())
>>> t
(('a', [1, 2]), ('b', [3, 4]))
>>> p = Paginator(t, 1)
>>> p.page(1).object_list
(('a', [1, 2]),)
>>> p.page(2).object_list
(('b', [3, 4]),)

更新:和循环也可以.那你能证明你有什么结构吗?

UPDATE: and looping also works. So can you show what structures do you have?

这篇关于使用字典的Django分页,其中键是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆