アプリのモデル ファイルに次の辞書があります。
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] - 2番目、リストの要素を返します)。私が理解していないのは、Pythonシェルでまったく同じことをすると異なる結果が得られる理由です。
私がdjango( TYPE_DICT[dict.type] )で行うようにすると、上記のように機能し、Pythonシェルでエラーが発生します。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
>>>
ここで何が問題なのですか?
アラン