How to save all instances in a single transaction in the peewee (python)?
Question: How to save all instances in a single transaction in the
[peewee](http://peewee.readthedocs.org/en/latest/) (python orm library)? For
example:

    
    
    from peewee import SqliteDatabase, Model, TextField
    
    DB_NAME = 'users.db'
    db = SqliteDatabase(os.path.join(os.path.dirname(__file__), DB_NAME))
    
    
    class Users(Model):
    
        user_id = IntegerField(index = True)
        name = TextField(null = True, index = True)
        password = TextField(null = True)
        description = TextField(null = True)
        class Meta:
            database = db
    
    if not Drugs.table_exists():
        Drugs.create_table()
    
    data_to_save = [('user1', 'pass1'), ('user2', 'pass2'), ('user3', 'pass3')]
    
    for user_name, user_password in data_to_save:
        user_data = Users.get_or_create(name=user_name, password=user_password)
        user_data.save()
    

how to rewrite in a single transaction?


Answer: You can wrap your query with "with" context manager
<http://peewee.readthedocs.org/en/latest/peewee/cookbook.html#working-with-
transactions>, so:

    
    
    with db.transaction():
      for user_name, user_password in data_to_save:
        user_data = Users.get_or_create(name=user_name, password=user_password)
        user_data.save()
    

