db.session.commit()
处停止,当我打印_form.project_list.data_时,我得到项目名称而不是外键。views.py
@app.route('/add_report/', methods=['GET', 'POST'])
def add_report():
form = AddReportForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
new_report = Report(
project_id=form.project_list.data,
issue=form.issue.data)
db.session.add(new_report)
db.session.commit()
flash('New report was successfully added.')
return redirect(url_for('projects'))
else:
flash('All fields are required.')
return redirect(url_for('projects'))
return render_template('project.html', form=form)
的 Models.py
class Project(db.Model):
project_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
date = db.Column(db.Date)
reports = db.relationship('Report', backref='project', lazy='dynamic')
def __repr__(self):
return self.name
class Report(db.Model):
report_id = db.Column(db.Integer, primary_key=True)
project_id = db.Column(db.Integer, db.ForeignKey('project.project_id'))
issue = db.Column(db.Text)
def __repr__(self):
return self.issue
forms.py
def get_projects():
return Project.query
class AddReportForm(Form):
project_list = QuerySelectField('Project', query_factory=get_projects)
issue = StringField('issue')
非常感谢
答案 0 :(得分:0)
报告表?你的意思是下拉列表吗?你试过吗
project_list = QuerySelectField('Project', query_factory=get_projects, get_label='project_id')
选中此question可将查询缩小为仅选择所需的列。
答案 1 :(得分:0)
最后我发现我的代码出了什么问题:)
<强> models.py 强>
class Project(db.Model):
project_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
date = db.Column(db.Date)
def __repr__(self):
return self.name
class Report(db.Model):
report_id = db.Column(db.Integer, primary_key=True)
project_id = db.Column(db.Integer, db.ForeignKey('project.project_id'))
projects = db.relationship('Project', backref='report')
issue = db.Column(db.Text)
def __repr__(self):
return self.issue
<强> views.py 强>
@app.route('/add_report/', methods=['GET', 'POST'])
def add_report():
form = AddReportForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
new_report = Report(
projects=form.project_list.data,
issue=form.issue.data)
db.session.add(new_report)
db.session.commit()
flash('New report was successfully added.')
return redirect(url_for('projects'))
else:
flash('All fields are required.')
return redirect(url_for('projects'))
return render_template('project.html', form=form)
forms.py 保持不变