自动创建选项列表

时间:2017-02-26 11:57:03

标签: python django

我正在django(v1.10.5)和python中制作一个在线影院预订应用程序。

models.py:

TheaterLocation = [
    (1, 'Naharlagun'),
]

FloorLevel = [
    (1, 'Ground Floor'),
    (2, 'Balcony'),
]

Row = [

]

Column = [

]

class Seat(models.Model):
    theater_location = models.PositiveIntegerField(choices=TheaterLocation)
    floor_level = models.PositiveIntegerField(choices=FloorLevel)
    row_id = models.PositiveIntegerField()
    column_id = models.PositiveIntegerField()

    @property
    def seat_id(self):
        return "%s : %s : %s : %s" % (self.theater_location, self.floor_level, self.row_id, self.column_id)

我想要做的是,自动创建RowColumn的选项列表:

Row = [
    (1, 'A'),
    (2, 'B'),
    ...
    ...
    (8, 'H'),
]

Column = [
    1,2,3,4,5, ... , 22
]

如何实现上述目标?

2 个答案:

答案 0 :(得分:1)

动态选择目前为can't be defined in the model definition,因此您需要在表单中传递callable to the corresponding ChoiceField

在您的情况下,生成行可能如下所示:

def get_row_choices():
    import string
    chars = string.ascii_uppercase
    choices = zip(range(1, 27), chars)
    # creates an output like [(1, 'A'), (2, 'B'), ... (26, 'Z')]
    return choices

class SeatForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SeatForm, self).__init__(*args, **kwargs)
        self.fields['row_id'] = forms.ChoiceField(choices=get_row_choices())

现在您可以像SeatAdmin这样使用此表单:

class SeatAdmin(admin.ModelAdmin):
    form = SeatForm

答案 1 :(得分:0)

我在这里假设您真正想要做的是将行和列链接到现有实体Row和Column。因为否则你会像上面实现的那样去(你已经有了)。但请记住,选择意味着元组。 查看以下文档: https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices

如果要将这些链接到现有的模型类,您所看到的是外键。