我有这个词典在我的应用程序模型文件:(重新)使用字典
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
>>>
所以这里有什么问题?
艾伦
感谢变量。这正是我一上床就意识到的:P – 2009-09-06 07:02:02