【问题标题】:Create a list of choices automatically自动创建选择列表
【发布时间】:2017-02-26 11:57:03
【问题描述】:

我正在用 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
]

我怎样才能像上面那样实现?

【问题讨论】:

  • 我很困惑。 “自动”是什么意思?
  • @hashcode55 我想使用 shell 或模板中的函数创建行和列。

标签: python django


【解决方案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

【讨论】:

  • 我怎样才能用你上面的代码和我的?我是否将 SeatForm 用于choices?喜欢row_d = models.PositiveIntegerField(choices=SeatForm)
  • 不,您不使用表单作为选择的值。文档中有关于表单的非常全面的信息:docs.djangoproject.com/en/1.10/topics/forms假设您当前正在使用管理员输入数据,您可以像这样编辑相关表单:stackoverflow.com/a/4466958/630877
【解决方案2】:

我在这里假设您真正想要做的是将行和列链接到现有实体行和列。因为否则您将按照上面的实现方式进行(您已经拥有它)。但请记住,选择是元组。 查看相关文档: https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices.

如果您想将它们链接到现有模型类,您正在查看的是外键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多