我的应用程序模型文件中有这本字典:
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 导入它。我正在创建一个字典列表以在我的视图中使用,如下所示:
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','Gift Wishlist')。
所以我可以理解它在做什么(在这种情况下,dict.type 等于 1,它应该返回我“购物清单”,但它返回我 [1] - 第二个,列表中的元素)。我不明白,为什么在 python shell 中做完全相同的事情会产生不同的结果。
像我在 django ( TYPE_DICT[dict.type] ) 中那样做,如上所述工作并在 python shell 中创建错误。在 python shell 中使用 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 shell 中做错了什么或不同。我所做的是:
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
>>>
那么这里有什么问题呢?
艾伦