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", forrelationship(cascade=...)on an async session:"save-update, merge, delete, expunge". With"all", your ownsession.refresh(obj)also expires the related objects. On an async session, the next read of one can then raiseMissingGreenlet. 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_ASYNCwith"delete-orphan": the cascade"all, delete-orphan"without"refresh-expire".
- class fastapi_restly.models.IDMixin#
Bases:
MappedAsDataclassDataclass 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.
- class fastapi_restly.models.PydanticJSON(type_: Any, none_as_null: bool = False)#
Bases:
TypeDecoratorA 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 columnPydanticJSON(Address), for each Pydantic model. Its type map haspydantic.BaseModel: PydanticJSON(pydantic.BaseModel), as SQLAlchemy usesenum.Enum: Enum(enum.Enum)for an enum. Your own entry forpydantic.BaseModelwins. Another type, such asdict[str, Address], needsmapped_column.The column validates the document when it loads a row, so
shop.addressis anAddress. 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 asTypeAdapter(type_)dumps it in JSON mode: a nested model becomes a dict, and adatetimebecomes 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 afloatfield 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 aWriteOnlyfield. The column would not store the value of such a field. It refuses aReadOnlyfield too, because a request writes the whole document and would replace the value. It also refuses a dataclass and an iterator type, such asIterable. It raisesRestlyConfigurationErrorwhen you define the column.In all else, the column works as SQLAlchemy’s
JSON.Noneis stored as JSONnull, andnone_as_null=Truestores SQLNULL. A change inside the document, such asshop.address.city = "Utrecht", is not saved: assign a new value. A query reads a part of the document as withJSON, as inShop.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.PydanticJSONBis the same column with PostgreSQL’sJSONB. For another JSON type, write a subclass that setsimplandcache_ok = True, as for any SQLAlchemyTypeDecorator.- Parameters:
type_ – The type of the document. It must be hashable, as the types above are.
none_as_null – Store
Noneas SQLNULL, as inJSON.
- Raises:
RestlyConfigurationError –
type_is not hashable, it has a part that the dump would mask or leave out, or it has aReadOnlyfield, 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
dictfordict[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:
PydanticJSONPydanticJSONwith PostgreSQL’sJSONB:class Shop(fr.IDMixin, Base): address: Mapped[Address] = mapped_column(fr.models.PydanticJSONB(Address))
PostgreSQL can compare two
JSONBdocuments, andJSONBhas more operators, such ascontainsandhas_key. ForMapped[Address]alone, putpydantic.BaseModel: fr.models.PydanticJSONB(pydantic.BaseModel)in thetype_annotation_mapof your base. SQLite has noJSONB.
- class fastapi_restly.models.ModelDefaults#
Bases:
AsyncAttrs,MappedAsDataclassRestly’s defaults for SQLAlchemy models, for your own declarative base.
Add it to your base class, before
DeclarativeBase:class Base(fr.ModelDefaults, DeclarativeBase): pass
Basestays yours: it has its own registry andMetaData, as with anyDeclarativeBase. 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=Trueon a model for the dataclass repr, which reads every field.A table name in snake_case from the class name:
BlogPostgetsblog_post. Set__tablename__on a model to choose another name.Mapped[datetime]asDateTime(timezone=True). Usemapped_column(DateTime())for a column without a time zone.An
enum.Enumas 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 aPydanticJSONcolumn: a JSON column that loads anAddress.awaitable_attrsfrom SQLAlchemy’sAsyncAttrs. An unloaded attribute can then be reached from plain async code,await obj.awaitable_attrs.items, where a bareobj.itemswould raiseMissingGreenlet. Views eager-load what the response schema names, so this is for the code that runs outside that: anafter_action_commithook, a custom business method.
Declare your own
metadataandtype_annotation_maponBaseas SQLAlchemy documents them. Your type entries win over Restly’s.Set dataclass options such as
eq=Trueon a model, not onBase. SQLAlchemy takes the options from the first dataclass class in a model’s bases, which is oftenIDMixin, so options onBasewould apply to some models only.Basewith options raisesRestlyConfigurationError.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). Withouteq=False, a model with the mixin compares fields, and comparing two objects can load a relationship. Withoutrepr=False, the model gets a dataclass repr instead of this one, and that repr can load a relationship too. Such a model raisesRestlyConfigurationError, unless it passeseq=Trueorrepr=Trueitself, or writes its own__eq__or__repr__.
- class fastapi_restly.models.TimestampsMixin#
Bases:
MappedAsDataclassDataclass mixin that adds
created_atandupdated_at, in UTC.Made for models on a base with
ModelDefaults. On another base, SQLAlchemy makes each model that uses it a dataclass.
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.