返回模型中的选择

时间:2013-03-15 14:41:26

标签: django

我有一个模特:

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。我认为这是关于我的回归。怎么解决?我需要在管理界面中的一个字符串中使用汽车名称和'sport'(或turbo等)。

感谢。

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分:2)

您应该使用self.get_d_type_display()

答案 2 :(得分:0)

您应该使用self.types_choices。这是因为types_choices是您的财产 Detail上课。

Django文档在如何使用选择方面有很好的模式:https://docs.djangoproject.com/en/dev/ref/models/fields/#choices

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

相关问题