User model and databases
This page describes how to configure your user model for fastapi-users using tortoise-orm. Read the official documentation Regarding this section to better understand how everything works, you can read the sqlalchemy guide for example. we will only cover here the specifics to use tortoise-orm.
Asynchronous driver¶
To work with your DBMS, you'll need to install the corresponding asyncio driver. The common choices are:
- For PostgreSQL:
pip install asyncpg
- For SQLite:
pip install aiosqlite
For the sake of this tutorial from now on, we'll use a simple SQLite database.
Create the User model¶
As for any Tortoise ORM model, we'll create a User
model.
1 2 3 4 5 6 7 |
|
As you can see, fastapi-users-tortoise provides a base class that will include base fields for our User
table. You can of course add you own fields there to fit to your needs!
Primary key is defined as UUID
By default, we use UUID as a primary key ID for your user. If you want to use another type, like an auto-incremented integer, you can use TortoiseBaseUserAccountModel
as base class and define your own id
column.
1 2 3 4 5 |
|
Implement a function to create the tables¶
You can use the tortoise orm generate_schemas
options to automatically create the table on app initialization,
something like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Warning
In production, it's strongly recommended to setup a migration system to update your SQL schemas. See Aerich.
Create the database adapter dependency¶
The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency.
1 2 3 4 5 6 7 8 9 10 |
|
Notice that we pass it the User
class, which is the actual Tortoise model.