python - Handling duplicates in SQLAlchemy -
i using sqlalchemy write data python database in sql. use code below write contents of 1 of tables sql, give me primary keys first table, table 1
, use when writing in data next table, table 2
foreign keys of table 2
mapped table 1
. however, writing function prevent duplicated data being written these tables if run script again.
base.metadata.create_all(engine, checkfirst=true) session = sessionmaker(bind=engine) session = session(bind=engine, expire_on_commit=false) # writing data table 1 session.add_all([ table1(name = 'euro'), table1(name = 'fed'), table1(name = 'aus'), table1(name = 'boe'), table1(name = 'canada')]) session.flush() session.commit() session = session(bind=engine, expire_on_commit=false) #obtaining primary keys table 1 listofindices = [] row in session.query(table 1): listofindices.append(row.id)
so, far code handling duplicates follows. however, not sure how obtain primary keys table 1
, @ same time prevent duplicated data being written it:
session = scoped_session(sessionmaker(bind=engine)) s = session() select_statement = s.execute('select count(*) table 1') result = select_statement.fetchone() table_exists = result[0] #does table 1 exist? if table_exists != 0: #dont know write here prevent duplicates table exists
Comments
Post a Comment