def save_db_objects(db_engine, db_objects):
"""Saves a collection of SQLAlchemy model objects to the database using a COPY command
Args:
db_engine (sqlalchemy.engine)
db_objects (list) SQLAlchemy model objects, corresponding to a valid table
"""
with tempfile.TemporaryFile(mode='w+') as f:
writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
for db_object in db_objects:
writer.writerow([
getattr(db_object, col.name)
for col in db_object.__table__.columns
])
f.seek(0)
postgres_copy.copy_from(f, type(db_objects[0]), db_engine, format='csv')
评论列表
文章目录