如何将WTForms下拉选择的数据正确读写至数据库?
解决WTForms下拉外键字段写入Customer表的问题
你的代码里有两个核心问题导致外键字段无法写入:一是创建Customer实例时没传入外键字段的值,二是WTForms的SelectField没配置类型转换,可能导致提交的ID不是整数类型。以下是具体修复步骤:
1. 修正WTForms的SelectField配置
在forms.py里,给所有外键对应的SelectField加上coerce=int和必填验证,确保提交的数值是整数类型(和数据库外键字段类型匹配):
class AddClient(FlaskForm): # 其他字段保持不变... condition_id = SelectField('condition', choices=[], validators=[InputRequired()], coerce=int) status_id = SelectField('status', choices=[], validators=[InputRequired()], coerce=int) payment_method_id = SelectField('payment_method', choices=[], validators=[InputRequired()], coerce=int) payment_type_id = SelectField('payment_type', choices=[], validators=[InputRequired()], coerce=int) submit = SubmitField("add")
2. 在创建Customer实例时传入外键字段值
在views.py的addclient函数里,创建new_client的时候,必须把下拉选择的外键ID字段加进去,否则数据库会因为外键字段非空而报错:
if formClient.validate_on_submit(): new_client = Customer( name=formClient.name.data, surname=formClient.surname.data, debt=formClient.debt.data, last_account=formClient.last_account.data, last_bill_of_the_month=formClient.last_bill_of_the_month.data, rate=formClient.rate.data, # 添加以下外键字段赋值 condition_id=formClient.condition_id.data, status_id=formClient.status_id.data, payment_method_id=formClient.payment_method_id.data, payment_type_id=formClient.payment_type_id.data ) db.session.add(new_client) db.session.commit() return redirect('/cust')
可选优化:添加SQLAlchemy关系映射
如果后续需要方便地通过Customer查询关联表的数据,可以在Models.py的Customer类里添加关系映射(不影响写入功能,但提升查询便捷性):
class Customer(db.Model): __tablename__ = 'customer' # 现有字段保持不变... # 添加关系映射 condition = db.relationship('Condition', backref=db.backref('customers', lazy=True)) status = db.relationship('Status', backref=db.backref('customers', lazy=True)) payment_method = db.relationship('Payment_method', backref=db.backref('customers', lazy=True)) payment_type = db.relationship('Payment_type', backref=db.backref('customers', lazy=True))
做完以上修改后,下拉选择的外键字段就能正确写入Customer表了。
内容的提问来源于stack exchange,提问作者Alexey
相关产品推荐
相关产品推荐

