python - Django 在模板中查找字典值并按日期排序

标签 python django dictionary

我正在使用此 View 将字典传递到我的模板 - views.py

def personlist(request, id):
    data = requests.get('http://127.0.0.1:8000/app_name/cities/' + id + '/persons/').json()
    context = RequestContext(request, {
    'persons': data['results'],'count': data['count'],
})
    @register.filter(name='lookup')
    def cut(value, arg):
    return value[arg]
    {{ mydict|lookup:item.name }}

    return render_to_response('template.html', context)

其中test_setresults内的字典。我正在使用此 View 以这种方式呈现模板 -

{% for person in persons %}
<a href="{% url 'person_detail' person.id %}"><p>{{person.name}}</p></a>
<p>{{person.test_set}}</p>
{% endfor %}

但这只是显示整个字典值 - [{u'test_name': u'test', u'date': u'2015-12-15T20:57:51.556145Z'}] 而我只想要约会。我尝试使用自定义模板来尝试使用 person.test_set.date 但它不起作用。

此外,给定名称和日期,有没有办法创建一个查找来显示每天/每周/每月添加的名称?

最佳答案

您似乎以错误的方式调用自定义模板。

@register.filter(name='lookup')
def cut(value, arg):
    return value.get(arg, '{} not found'.format(arg))

{{ person.test_set|lookup:'date' }}

我还修改了返回值,以便至少在无法找到 key 时返回一条消息。

<小时/>

你的评论让我意识到 test_set 不是字典,它是字典的列表。我想你想先迭代这些然后获取日期

{% for test in test_set %}
     {{ test.date }}
     {# or {{ test|lookup:'date' }} #}
{% endfor %}

关于python - Django 在模板中查找字典值并按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306603/

相关文章:

python - 如何修复:unsatisfiableerror: the following specifications were found to be in conflict

python - “builtin_function_or_method”对象不可订阅

python - 如何将 View 中的字符串参数传递给 url?

python - Django 时区 : feeling a bit confused

python - 规范错误: nested renamer is not supported error while using agg function on dictionary

c++ - TBB concurrent_hash_map operator[] 或类似访问?

Python开发-elementtree XML和字符串操作

python - 如何在python3x的套接字上正确发送字典的内容?

django - 处理唯一 NULL 值的正确方法

c++ - 我应该为 map 使用哪种数据结构? (C++)