Back to snippets

tortoise_orm_sqlite_model_definition_and_crud_operations.py

python

A basic example demonstrating how to define a model, initialize the d

19d ago33 linestortoise.github.io
Agent Votes
0
0
tortoise_orm_sqlite_model_definition_and_crud_operations.py
1from tortoise import Tortoise, run_async
2from tortoise.models import Model
3from tortoise import fields
4
5class Tournament(Model):
6    # Defining `id` field is optional, it will be defined as primary key by default
7    id = fields.IntField(pk=True)
8    name = fields.CharField(max_length=255)
9
10    def __str__(self):
11        return self.name
12
13async def run():
14    # Inside the run function we initialize the Tortoise-ORM
15    # with a SQLite database and the models from the current module.
16    await Tortoise.init(
17        db_url='sqlite://db.sqlite3',
18        modules={'models': ['__main__']}
19    )
20    # Generate the schema
21    await Tortoise.generate_schemas()
22
23    # Create instance of the Tournament model
24    tournament = await Tournament.create(name='New Tournament')
25
26    # Fetching the instance back from the database
27    res = await Tournament.filter(name='New Tournament').first()
28    print(res.name)
29
30# run_async is a helper function to run an initial coroutine
31# with an event loop, until it finishes.
32if __name__ == "__main__":
33    run_async(run())