2017-02-26 68 views
0

我在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) 

我想要做的是,为自动创建一个选项列表和Column这样的:

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

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

我怎样才能做到像上述?

+0

我很困惑。 “自动”是什么意思? – hashcode55

+0

@ hashcode55我想使用shell或模板中的函数创建行和列。 – Aamu

回答

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

如何使用您的上述代码与我的?我是否将SeatForm用于“选择”?像'row_d = models.PositiveIntegerField(choices = SeatForm)' – Aamu

+0

不,你不使用表单作为选择的值。文档中有关于表单的全面信息:https://docs.djangoproject.com/en/1.10/topics/forms/ 假设您正在使用管理员输入数据,则可以编辑相关表单这:http://stackoverflow.com/a/4466958/630877 – arie

0

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

如果你想链接到现有的模型类,你正在看的是外键。