2016-05-17 62 views
1

尽管我已经使用自定义过滤器通过变量键访问字典的值,但我无法这样做。以下是代码片段。无法使用Django模板中的过滤器使用变量键访问上下文字典值

view.py

def DBConnect(request): 
    c = {} 
    c['dbs'] = get_all_db() #returns an array of db. 
    for db in c['dbs']: 
     c[db] = get_all_tables(db) #returns all the tables in db and storing in context dictionary with db name as key. 

    return render_to_response('test.html', c) 

作为一个实施例C将包含如下: C = { 'DBS':[u'db1' ,u'db2 '],u'db1':[U” TB1' ,u'tb2 '],u'db2':[u'tb21' ,u'tb22' ]}

app_filter.py

@filter.filter 
def get_item(dictionary, key): 
    return dictionary.get(key) 

的test.html .... 。 ...

{%for db in dbs%} 
    do something with {{db}} <- this is fine, I am getting all the dbs here. 
    {{ c | get_item : db }} <- This code is not working, If I directly pass dbname literal than it is working fine. 
{% endfor %} 

请建议我是否应以不同的方式通过上下文来解决此问题。 在此先感谢。

+0

你通过“星展银行”到测试模板?根据上面的代码,您传递的是'c',它是'dbs'作为其中一个关键字的字典。 –

+0

谢谢Rohan和AKS的回复。我对Django框架相当陌生。我将实施这些解决方案并将标记为答案。我非常确定这两种解决方案都可以完成这项工作。谢谢AKS的解释,这真的有助于我理解与Django相关的一些事情。再次感谢你们。 +1为你们俩。:-) – Amit

+0

@Amit:感谢您的评论,我们很乐意提供帮助。还请阅读[当某人回答我的问题时该怎么办?](http://stackoverflow.com/help/someone-answers)。 – AKS

回答

0

由于c是一个方面,它是不是在模板中直接使用。什么是可用的是按键/值,您在上下文中设置,即如果你的环境就像下面:

c = {'dbs':[u'db1', u'db2'], u'db1' : [u'tb1', u'tb2'], u'db2' : [u'tb21', u'tb22']} 

您将能够访问dbsdb1db2为模板里面的变量。这里键被翻译成变量,并且上下文中的值是这些变量的值,例如,当您访问dbs时,您直接访问c['dbs']

考虑到你在做什么,我会选择做像以下:现在

def DBConnect(request): 
    c = {} 
    dbs = get_all_db() #returns an array of db. 
    c['dbtbls'] = {db: get_all_tables(db) for db in dbs} 
    return render_to_response('test.html', c) 

,在模板中可以直接访问dbtbls.items

{% for db, tbls in dbtbls.items %} 
    do something with {{ db }} here. 
    {{ tbls }} # this is the list of all the tables in the db 
{% endfor %} 
0

在django模板中,上下文变量直接从dbs中看到。你不需要像访问一样使用字典。

可以稍微改变的背景下,以适应您的代码

def DBConnect(request): 
    c = {} 
    c['dbs'] = get_all_db() #returns an array of db. 
    c['dbtables'] = {} 
    for db in c['dbs']: 
     c['dbtables'][db] = get_all_tables(db) 

    return render_to_response('test.html', c) 

然后在模板你可以使用

{%for db in dbs%} 
    do something with {{db}} here. 
    {{ dbtables | get_item : db }} 
{% endfor %} 
相关问题