Models API#

fastapi_restly.models provides ModelDefaults, which adds Restly’s defaults to your own declarative base, and the model mixins IDMixin and TimestampsMixin. Models shows how to use them. It provides PydanticJSON and PydanticJSONB, JSON columns that hold a document of a type that Pydantic validates, such as a model. It also provides two cascades for relationships on an async session, CASCADE_ALL_ASYNC and CASCADE_ALL_DELETE_ORPHAN_ASYNC.

fastapi_restly.models.CASCADE_ALL_ASYNC = 'save-update, merge, delete, expunge'#

The cascade "all" without "refresh-expire", for relationship(cascade=...) on an async session: "save-update, merge, delete, expunge". With "all", your own session.refresh(obj) also expires the related objects. On an async session, the next read of one can then raise MissingGreenlet. Restly’s own save after a write refreshes by attribute name and does not cascade, so "all" is safe on Restly’s write paths. See SQLAlchemy’s Preventing Implicit IO when Using AsyncSession.

fastapi_restly.models.CASCADE_ALL_DELETE_ORPHAN_ASYNC = 'save-update, merge, delete, expunge, delete-orphan'#

CASCADE_ALL_ASYNC with "delete-orphan": the cascade "all, delete-orphan" without "refresh-expire".

class fastapi_restly.models.IDMixin#

Bases: MappedAsDataclass

Dataclass mixin adding an auto-incrementing integer id primary key.

Made for models on a base with ModelDefaults. On another base, SQLAlchemy makes each model that uses it a dataclass.

id: Mapped[int] = mapped_column(...)#

The primary key: an integer that the database generates when it inserts the row. The constructor does not take it, and it is None until the session flushes the new object.

class fastapi_restly.models.PydanticJSON(type_: Any, none_as_null: bool = False)#

Bases: TypeDecorator

A JSON column that holds a Pydantic type, such as a model:

class Address(pydantic.BaseModel):
    street: str
    city: str


class Shop(fr.IDMixin, Base):
    address: Mapped[Address]
    branches: Mapped[dict[str, Address]] = mapped_column(
        fr.models.PydanticJSON(dict[str, Address])
    )

On a base with ModelDefaults, Mapped[Address] alone gives the column PydanticJSON(Address), for each Pydantic model. Its type map has pydantic.BaseModel: PydanticJSON(pydantic.BaseModel), as SQLAlchemy uses enum.Enum: Enum(enum.Enum) for an enum. Your own entry for pydantic.BaseModel wins. Another type, such as dict[str, Address], needs mapped_column.

The column validates the document when it loads a row, so shop.address is an Address. A write validates the value too, so a dict works as well, and so does another model with the same fields. Then it dumps the value as TypeAdapter(type_) dumps it in JSON mode: a nested model becomes a dict, and a datetime becomes text. A NaN or an infinity becomes the text "NaN", "Infinity" or "-Infinity", because JSON has no number for it. The keys are the names of the fields, not their aliases. A load reads the stored JSON data in lax mode, so a strict model reads it back too, and a float field reads that text as a number.

The column refuses a type with a secret, such as SecretStr, or with a field that a dump leaves out, such as a WriteOnly field. The column would not store the value of such a field. It refuses a ReadOnly field too, because a request writes the whole document and would replace the value. It also refuses a dataclass and an iterator type, such as Iterable. It raises RestlyConfigurationError when you define the column.

In all else, the column works as SQLAlchemy’s JSON. None is stored as JSON null, and none_as_null=True stores SQL NULL. A change inside the document, such as shop.address.city = "Utrecht", is not saved: assign a new value. A query reads a part of the document as with JSON, as in Shop.address["city"].as_string() == "Utrecht". A dict or a model in a query is dumped, but not validated, because it can be a part of a document.

PydanticJSONB is the same column with PostgreSQL’s JSONB. For another JSON type, write a subclass that sets impl and cache_ok = True, as for any SQLAlchemy TypeDecorator.

Parameters:
  • type_ – The type of the document. It must be hashable, as the types above are.

  • none_as_null – Store None as SQL NULL, as in JSON.

Raises:

RestlyConfigurationError – type_ is not hashable, it has a part that the dump would mask or leave out, or it has a ReadOnly field, which a write would replace.

hashable = False#

As for JSON: a document can be a dict, which has no hash.

property python_type: type#

The class of the document, such as dict for dict[str, Address].

Raises:

NotImplementedError – The type is a union, Any, or another type that is not one class. SQLAlchemy raises it for such a type too.

class fastapi_restly.models.PydanticJSONB(type_: Any, none_as_null: bool = False)#

Bases: PydanticJSON

PydanticJSON with PostgreSQL’s JSONB:

class Shop(fr.IDMixin, Base):
    address: Mapped[Address] = mapped_column(fr.models.PydanticJSONB(Address))

PostgreSQL can compare two JSONB documents, and JSONB has more operators, such as contains and has_key. For Mapped[Address] alone, put pydantic.BaseModel: fr.models.PydanticJSONB(pydantic.BaseModel) in the type_annotation_map of your base. SQLite has no JSONB.

class fastapi_restly.models.ModelDefaults#

Bases: AsyncAttrs, MappedAsDataclass

Restly’s defaults for SQLAlchemy models, for your own declarative base.

Add it to your base class, before DeclarativeBase:

class Base(fr.ModelDefaults, DeclarativeBase):
    pass

Base stays yours: it has its own registry and MetaData, as with any DeclarativeBase. Your models get:

  • A dataclass constructor that takes keyword arguments only. Type checkers accept a required field after a field with a default.

  • Equality by identity, as for any SQLAlchemy model: two objects are equal only when they are the same object. So a model object can go in a set, and comparing objects never loads a relationship.

  • A repr that shows the loaded columns and never loads anything, so it works in async code. Pass repr=True on a model for the dataclass repr, which reads every field.

  • A table name in snake_case from the class name: BlogPost gets blog_post. Set __tablename__ on a model to choose another name.

  • Mapped[datetime] as DateTime(timezone=True). Use mapped_column(DateTime()) for a column without a time zone.

  • An enum.Enum as a string column of up to 64 characters that stores the member’s name, not a database enum type. A new member then needs no migration.

  • A Pydantic model, as in Mapped[Address], as a PydanticJSON column: a JSON column that loads an Address.

  • awaitable_attrs from SQLAlchemy’s AsyncAttrs. An unloaded attribute can then be reached from plain async code, await obj.awaitable_attrs.items, where a bare obj.items would raise MissingGreenlet. Views eager-load what the response schema names, so this is for the code that runs outside that: an after_action_commit hook, a custom business method.

Declare your own metadata and type_annotation_map on Base as SQLAlchemy documents them. Your type entries win over Restly’s.

Set dataclass options such as eq=True on a model, not on Base. SQLAlchemy takes the options from the first dataclass class in a model’s bases, which is often IDMixin, so options on Base would apply to some models only. Base with options raises RestlyConfigurationError.

For the same reason, a dataclass mixin of your own declares the options of fr.IDMixin: class Stamped(MappedAsDataclass, kw_only=True, eq=False, repr=False). Without eq=False, a model with the mixin compares fields, and comparing two objects can load a relationship. Without repr=False, the model gets a dataclass repr instead of this one, and that repr can load a relationship too. Such a model raises RestlyConfigurationError, unless it passes eq=True or repr=True itself, or writes its own __eq__ or __repr__.

class fastapi_restly.models.TimestampsMixin#

Bases: MappedAsDataclass

Dataclass mixin that adds created_at and updated_at, in UTC.

Made for models on a base with ModelDefaults. On another base, SQLAlchemy makes each model that uses it a dataclass.

created_at: Mapped[datetime] = mapped_column(...)#

When the row was created, in UTC. The model sets it to the current time when you create the object. The database sets it when SQL that leaves it out inserts a row.

updated_at: Mapped[datetime] = mapped_column(...)#

When the row last changed, in UTC. The model sets it when you create the object, and again in each UPDATE that SQLAlchemy runs for the row. The database sets it when SQL that leaves it out inserts a row.

See also

Models shows how to add Restly’s defaults to your own declarative base and how to change one. Use your existing models shows Restly views on the models you already have.