0

我有一个模型:

class Detail(models.Model):
    types_choices = (
        (1, 'Sport'),
        (2, 'Turbo'),
        (3, 'Turbo++'),
    )   
    car = models.ForeignKey(Car)
    d_type = models.PositiveIntegerField(choices=types_choices, max_length=1)
    def __unicode__(self):
        return u"%s, %s" % (self.car.name, types_choices[self.d_type][1])

在管理界面中出现错误:global name 'types_choices' is not defined. 我认为这是关于我的回归。如何解决?我需要在管理界面的一个字符串中包含汽车名称和“运动”(或涡轮增压等)。

谢谢。

4

3 回答 3

2

你忘记了自己。

class Detail(models.Model):
    types_choices = (
        (1, 'Sport'),
        (2, 'Turbo'),
        (3, 'Turbo++'),
    )   
    car = models.ForeignKey(Car)
    d_type = models.PositiveIntegerField(choices=types_choices, max_length=1)
    def __unicode__(self):
        return u"%s, %s" % (self.car.name, self.types_choices[self.d_type][1])
于 2013-03-15T14:46:31.063 回答
2

你应该使用self.get_d_type_display().

于 2013-03-15T14:46:56.470 回答
0

你应该使用self.types_choices. 这是因为types_choices是您 Detail班级的一个属性。

Django 文档对如何使用选项有一个很好的模式:https ://docs.djangoproject.com/en/dev/ref/models/fields/#choices

您还可以使用self.get_d_type_display()获取选择字段的详细名称。

于 2013-03-15T14:47:23.533 回答