Flask-sqlalchemy check if data already exits in table before Inserting
Question:
I am trying to insert some values into table using flask sqllite methods but I am not sure how to make the statement equivalent to Insert into table if not exits , the below method adds the data but if already present I want to ignore it kindly guide on the same
pl1 = mydb(employee_name='JOhn doe')
db.session.add(pl1)
db.commit()
Answers:
Maybe this
pl1 = mydb(employee_name='JOhn doe')
if not db_session.query(mydb).filter_by(employee_name='JOhn doe').first():
db_session.add(pl1)
db_session.commit()
I usually use db
or db_session
. I don’t know if your db.session
is a typo. In any case it should be easy to adjust the syntax.
I am trying to insert some values into table using flask sqllite methods but I am not sure how to make the statement equivalent to Insert into table if not exits , the below method adds the data but if already present I want to ignore it kindly guide on the same
pl1 = mydb(employee_name='JOhn doe')
db.session.add(pl1)
db.commit()
Maybe this
pl1 = mydb(employee_name='JOhn doe')
if not db_session.query(mydb).filter_by(employee_name='JOhn doe').first():
db_session.add(pl1)
db_session.commit()
I usually use
db
ordb_session
. I don’t know if yourdb.session
is a typo. In any case it should be easy to adjust the syntax.