2009-09-05 22 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是我傳遞給模板

希望這有助於其他人