python – 如何在Flask-Admin中将字符串模型字段转换为选择输入?

我的SQLAlchemy模型中有一个字符串字段,我想在Flask-Admin中显示一个带有几个选项的选择框,而不是标准文本字段.

class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_field = db.Column(db.String(128))  # Field I would like to be choices


class MyModelView(ModelView):
    """
    Admin manager for MyModel
    """

    # Which option should I use here?

    def __init__(self):
        super(MyModelView, self).__init__(MyModel, db.session)
最佳答案
它最终成为form_overrides和form_args的组合. form_overrides告诉表单使用select字段,form_args允许您传递选项和其他选项.

class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_field = db.Column(db.String(128))


class MyModelView(ModelView):
    """
    Admin manager for MyModel
    """

    form_overrides = dict(
        my_field=SelectField
    )
    form_args = dict(
        my_field=dict(
            choices=[
                ('choice_1', 'Choice 1'),
                ('choice_2', 'Choice 2')
            ]
        )
    )
    def __init__(self):
        super(MyModelView, self).__init__(MyModel, db.session)

转载注明原文:python – 如何在Flask-Admin中将字符串模型字段转换为选择输入? - 代码日志