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 导入它。我正在创建一个字典列表以在我的视图中使用,如下所示:

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
>>>

那么这里有什么问题呢?

艾伦

4

4 回答 4

6

TYPE_DICT在模型文件中的不是字典:它是元组的元组。

如果您愿意,您可以轻松地从中制作字典:

TYPE_DICT_DICT = dict(TYPE_DICT)

那么您可以将TYPE_DICT_DICT其用作真正的字典。

于 2009-09-05T21:02:22.780 回答
0

首先,将您的元组修改为字典格式。然后,在 django 模板中访问时,您需要将该字典的键假定为属性...假设这是字典

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

在 django 模板中访问此字典时,您应该像这样使用

TYPE_DICT.1
于 2009-09-06T03:04:33.243 回答
0

您好,我从昨天开始就尝试这样做,今天我意识到您可以制作自己的过滤器,以便您可以传递字典键(存储在数据库中)。

我试图让它与状态一起使用,因为我在很多模型中都使用它,所以我将它添加到设置中,所以它是这样的:

在 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 是我传递给模板的变量

希望这对其他人有帮助

于 2012-01-09T23:57:46.843 回答
-1

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

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

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

于 2009-09-05T21:03:35.980 回答