2009-09-05 23 views
1

我有这个词典在我的应用程序模型文件:(重新)使用字典

TYPE_DICT = (
    ("1", "Shopping list"), 
    ("2", "Gift Wishlist"), 
    ("3", "test list type"), 
    ) 

模式,使用这种字典是这样的:

class List(models.Model): 
    user = models.ForeignKey(User) 
    name = models.CharField(max_length=200) 
    type = models.PositiveIntegerField(choices=TYPE_DICT) 

我想重新使用它在我的意见,并从apps.models进口它。我创建dictioneries名单在我看来,用这样的:

bunchofdicts = List.objects.filter(user=request.user) 
    array = [] 
    for dict in bunchofdicts: 
     ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' } 
     array.append(ListDict) 

,当我在我的模板中使用这个列表,然后它给了我非常奇怪的结果。 而不是返回列表类型(购物清单)它返回我('2','礼物愿望清单')。所以我可以理解它在做什么(在这种情况下,dict.type等于1,它应该返回给我“购物清单”,但它返回我[1] - 第二个元素在列表中)。我不明白,为什么在python shell中完全一样的东西给出了不同的结果。

按照我在django(TYPE_DICT [dict.type])中所做的方式工作,如上所述,并在python shell中创建错误。在python外壳采用TYPE_DICT [STR(dict.type)工作得很好,但在Django创建此错误:

TypeError at /list/ 

tuple indices must be integers, not str 

Request Method:  GET 
Request URL: http://127.0.0.1/list/ 
Exception Type:  TypeError 
Exception Value:  

tuple indices must be integers, not str 

Exception Location:  /home/projects/tst/list/views.py in list, line 22 
Python Executable: /usr/bin/python 
Python Version:  2.6.2 

也许我做错事或在Python壳上的不同。我做的是:

python 
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'} 
>>> print dict[1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 1 
>>> print dict[str(1)] 
shoppinglist 
>>> x = 1 
>>> print dict[x] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
KeyError: 1 
>>> print dict[str(x)] 
shoppinglist 
>>> 

所以这里有什么问题?

艾伦

回答

6

TYPE_DICT在你的模型文件不是一本字典:这是一个元组的元组。

你可以很容易地从它的字典但如果你想:

TYPE_DICT_DICT = dict(TYPE_DICT) 

那么你可以使用TYPE_DICT_DICT作为一个真正的字典。

+0

感谢变量。这正是我一上床就意识到的:P – 2009-09-06 07:02:02

-1

您正在创建一个元组,而不是字典。

TYPE_DICT = { 
    1: "Shopping list", 
    2: "Gift Wishlist", 
    3: "test list type", 
} 

是一个字典(但这不是什么选择想要的)。

0

首先,修改您的元组字典格式.. 然后,在Django模板访问,当你需要假设字典作为一个属性的关键...让我们说这是字典

TYPE_DICT = { 
    1: 'Shopping list', 
    2: 'Gift Wishlist', 
    3: 'test list type', 
} 

进入本词典在Django模板时,你应该使用这样

TYPE_DICT.1 
0

你好,我试图做到这一点,因为昨天和今天我意识到你可以make your own filter,这样就可以把字典键(存储在d atabase)。

我试图让这个与各国合作,因为我用这个在很多我把它添加到设置模式所以它是这样的:

settings.py中

... 
CSTM_LISTA_ESTADOS = (
    ('AS','Aguascalientes'), 
    ('BC','Baja California'), 
... 
    ('YN','Yucatan'), 
    ('ZS','Zacatecas') 
) 
... 

在我customtags.py

@register.filter(name='estado') 
def estado(estado): 
    from settings import CSTM_LISTA_ESTADOS 
    lista_estados = dict(CSTM_LISTA_ESTADOS) 
    return lista_estados[estado] 

在我的模板basicas.html

{{oportunidad.estado|estado}} 

oportunidad是我传递给模板

希望这有助于其他人