Wtforms QueryselectField 不传递 id

Wtforms QueryselectField doesn't pass id

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')

非常感谢

举报table?你的意思是下拉列表?你试过了吗

project_list = QuerySelectField('Project', query_factory=get_projects, get_label='project_id')

选中此 question 将您的查询减少到仅 select 所需的列。

终于我发现我的代码出了什么问题:)

  • 我在报告 table 中使用 project_id(外键)来获取项目 ID(form.project_list.data)而不是项目(关系)。所以我对 models.py 和 views.py.
    做了一些修改 可怜的forms.py,我还以为是你的错呢!

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保持不变