Django RelatedManager将元组转换为Unicode字符串?

时间:2012-04-14 18:37:49

标签: python django

为了帮助自己学习Python,我正在使用Django编写一个简单的问题跟踪器。

我有两个简单的类(为了简洁而留下一些代码),IssueVersion

有一个ISSUE_STATE元组用于维护Issue的状态:

ISSUE_STATE = (
    ('p', 'In Progress'),
    ('o', 'Open'),
    ('r', 'Resolved'),
    ('c', 'Closed'),
)

它保存在Issue中,如此:

class Issue(models.Model):
    state = models.CharField(max_length=1, choices=ISSUE_STATE)
    fix_version = models.ForeignKey(Version, related_name='issuesAsFix', null=True, blank=True, default=None)

(正如您所看到的,Version维护着Issue个对象的列表。)

问题:

当我访问单个Issue实例的状态时,它将作为元组返回。当我访问由Issue对象提供的Version状态时,它将作为Unicode字符串返回:

>>> v = Version()
>>> v.save()

>>> i = Issue()
>>> i.fix_version = v
>>> i.state = ISSUE_STATE[1]
>>> i.save()

>>> i.state
('o', 'Open')
>>> v.issuesAsFix.all()[0].state
u"('o', 'Open')"

>>> i == v.issuesAsFix.all()[0]
True
>>> i is v.issuesAsFix.all()[0]
False

为什么state的{​​{1}}变量作为Issue的子属性进行访问?

提前致谢!

1 个答案:

答案 0 :(得分:1)

>>> i.state = ISSUE_STATE[1]

此行不正确。它应该是:

>>> i.state = ISSUE_STATE[1][0]