【问题标题】:dynamic WTForms SelectField shows the column-title of table in the db动态 WTForms SelectField 显示数据库中表的列标题
【发布时间】:2020-02-29 05:07:18
【问题描述】:

我正在尝试通过烧瓶 sql-alchemy 从 SQL 表“学校”中提取数据到 SelectField:

表格:

school_choices = [(School.id, School.name) for school in School.query.all()]
school = SelectField('Your school', validators=[DataRequired()], choices=school_choices)

路线:

def register():
if current_user.is_authenticated:
    return redirect(url_for('home'))
form = RegistrationForm()
if form.validate_on_submit():
    hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
    user = User(username=form.username.data, email=form.email.data, password=hashed_password, school=form.school.data)
    db.session.add(user)
    db.session.commit()
    flash('Your account has been created! You are now able to log in', 'success')
    return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)

型号:

class School(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)

但是,它不知何故只显示“School.name”,就像它在表单中的写法一样。 此外,它应该显示的条目数是正确的(3 个,因为数据库中有 3 个学校条目)

【问题讨论】:

    标签: flask dynamic sqlalchemy flask-sqlalchemy flask-wtforms


    【解决方案1】:

    问题在于您的列表理解,它构建了选择字段的值,以及在类上呈现列属性与类实例之间的差异:

    school_choices = [(School.id, School.name) for school in School.query.all()]
    

    在上述理解中,每个循环中的school(小写's')是类School(大写'S')的一个实例。

    在 sqlalchemy 中,类(不是类的实例)上的列属性的字符串表示返回列的数据库标识,例如:"<tablename>.<columnname>",或者在这种情况下为 "school.name"。这就是查询的构建方式,例如尝试运行print(School.__table__.select()),它将打印SELECT school.id, school.name FROM School。该查询中的列标识来自“字符串化” Column 实例。

    但是,当我们访问类实例的列属性时,例如school = School(name="myschool"),我们获取存储在数据库中的列的值。例如。 print(school.school) # myschool.

    查看上面的列表理解,您为数据库中的每个 school 实例创建了一个 (School.id, School.name) 元组。请注意“School”的大写“S”,这意味着当您的模板呈现时,您最终会为数据库中的每个学校呈现列的数据库标识的字符串表示形式。答案很简单,只需将您的理解改为:

    school_choices = [(school.id, school.name) for school in School.query.all()]
    

    ...但是在一般情况下使用 sqlalchemy 和 python 时,了解它们之间的区别是相当重要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      相关资源
      最近更新 更多