I have been refactoring some code to use SQLALchemy but have been using Flask framework so have been using the extension Flask-SQLAlchemy.
I run a query on my model that has two inner join and where clauses on it. This can be seen below;
rows = Master.query.join(
Company,
Master.company == Company.company_id
).join(
Countries,
Master.country_id == Countries.country_id
).filter(
((Master.relevant == 1) | (Master.relevant == 0)),
((Master.displayed == 0) | (Master.displayed == 1)),
Master.sent == 0,
Master.date >= '2017-12-31 23:59:59'
).with_entities(
Master.id,
Countries.country_name,
Company.company_name,
Master.date,
Master.info,
Master.link
).order_by(Master.date.desc())
However as I want to populate flask-wtforms I have created the form class;
class BusinessOps(FlaskForm):
id = TextField('id', [Required()])
company = TextField('company', [Required()])
country = TextField('country', [Required()])
date = TextField('date', [Required()])
info = TextField('info', [Required()])
link = TextField('link', [Required()])
then in my view I have the following;
@app.route('/business-ops', methods=['GET', 'POST'])
@login_required
def buisness_opportunities():
rows = Master.query.join(
Company,
Master.company == Company.company_id
).join(
Countries,
Master.country_id == Countries.country_id
).filter(
((Master.relevant == 1) | (Master.relevant == 0)),
((Master.displayed == 0) | (Master.displayed == 1)),
Master.sent == 0,
Master.date >= '2017-12-31 23:59:59'
).with_entities(
Master.id,
Countries.country_name,
Company.company_name,
Master.date,
Master.info,
Master.link,
# Master.relevant,
# Master.displayed,
# Master.sent
).order_by(Master.date.desc())
print(type(rows))
form = BusinessOps(obj=rows)
print(form.data) #returns dict with null values for keys
return render_template('business-ops.html', form=form)
Originally when I run this code together, I received no output, so I tested by printing form.data and saw it returned me an empty value dictionary. So I then printed the type of rows and it returned me <class 'flask_sqlalchemy.BaseQuery'>.
After reading here I understood that I would be able to pre-populate the data in my form from the data in the query?
form = BusinessOps(obj=rows.first())might do the trick. I'm pretty sure you need to pass the object not just the query to the form. Though I've never actually tried to populate directly from a query.