跳转至

插入

insert

你可以调用模型实例的 insert 方法来将其插入到数据库中:

    user = User(name="user 1")
    await user.insert()

insert_many

使用模型类的 insert_many 来同时插入多条数据:

1
2
3
4
    user2 = User(name="user 2")
    user3 = User(name="user 3")
    user4 = User(name="user 4")
    await User.insert_many(user2, user3, user4)

完整代码

本章完整示例代码
import cherry

db = cherry.Database("sqlite+aiosqlite:///:memory:")


class User(cherry.Model):
    id: cherry.AutoIntPK = None
    name: str
    age: int = 18

    cherry_config = cherry.CherryConfig(tablename="user", database=db)


async def main():
    await db.init()

    user = User(name="user 1")
    await user.insert()

    user2 = User(name="user 2")
    user3 = User(name="user 3")
    user4 = User(name="user 4")
    await User.insert_many(user2, user3, user4)


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())