Skip to content

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
from fastapi_users_tortoise import TortoiseBaseUserAccountModelUUID
from tortoise import fields


class User(TortoiseBaseUserAccountModelUUID):
    full_name = fields.CharField(max_length=255, null=True)
    short_name = fields.CharField(max_length=255, null=True)

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
from fastapi_users_tortoise import TortoiseBaseUserAccountModel
from tortoise import models, fields

class User(TortoiseBaseUserAccountModel, models.Model):
    id = fields.IntField(pk=True)

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
from tortoise import Tortoise

async def init():
    # Here we create a SQLite DB using file "db.sqlite3"
    #  also specify the app name of "models"
    #  which contain models from "app.models"
    await Tortoise.init(
        db_url='sqlite://db.sqlite3',
        modules={'models': ['app.models']}
    )
    # Generate the schema
    await Tortoise.generate_schemas()

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
from fastapi_users_tortoise import TortoiseBaseUserAccountModelUUID, TortoiseUserDatabase
from tortoise import fields


class User(TortoiseBaseUserAccountModelUUID):
    full_name = fields.CharField(max_length=255, null=True)
    short_name = fields.CharField(max_length=255, null=True)

async def get_user_db():
    yield TortoiseUserDatabase(User)

Notice that we pass it the User class, which is the actual Tortoise model.