sqlmodel-async-factory
factory_boy factories that build and persist SQLModel objects through an async SQLAlchemy session.
factory_boy ships SQLAlchemyModelFactory, which calls session.add() and
session.commit() synchronously. Against an AsyncSession those calls either
raise MissingGreenlet or silently never flush. AsyncSQLModelFactory keeps
the whole factory_boy declaration language (Sequence, LazyAttribute,
Faker, SubFactory, sqlalchemy_get_or_create) and makes the create step
awaitable.
Why it exists
It was extracted from the test suite of a production FastAPI application whose
database access is async end to end. Every attempt to reuse the stock
SQLAlchemy factory ended in a copy of the same twenty lines of glue in each
project, so the glue became a package, with the SubFactory case handled once
and properly: a sub-factory returns an asyncio.Task rather than an instance,
and the parent factory has to await it before passing it to the model
constructor.
It targets SQLModel rather than plain SQLAlchemy: the lookups go through
AsyncSession.exec(), which SQLModel adds on top of SQLAlchemy's session and
which returns the model instances instead of rows.
Installation
uv add sqlmodel-async-factory
or:
pip install sqlmodel-async-factory
Usage
import factory
from sqlmodel_async_factory import AsyncSQLModelFactory
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, Relationship, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession
class Team(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(unique=True)
heroes: list["Hero"] = Relationship(back_populates="team")
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
team_id: int | None = Field(default=None, foreign_key="team.id")
team: Team | None = Relationship(
back_populates="heroes", sa_relationship_kwargs={"lazy": "selectin"}
)
engine = create_async_engine("postgresql+asyncpg://localhost/heroes")
session = AsyncSession(engine, expire_on_commit=False)
class TeamFactory(AsyncSQLModelFactory):
class Meta:
model = Team
sqlalchemy_session = session
sqlalchemy_get_or_create = ("name",)
name = factory.Sequence(lambda n: f"team-{n}")
class HeroFactory(AsyncSQLModelFactory):
class Meta:
model = Hero
sqlalchemy_session = session
name = factory.Sequence(lambda n: f"hero-{n}")
team = factory.SubFactory(TeamFactory)
Then, in a test:
async def test_hero_belongs_to_a_team():
hero = await HeroFactory.create()
assert hero.team.name.startswith("team-")
heroes = await HeroFactory.create_batch(3, team=hero.team)
assert all(other.team_id == hero.team_id for other in heroes)
create and create_batch are coroutines and must be awaited. The rest of the
factory_boy API is unchanged.
Session settings
Two session settings matter:
expire_on_commit=False.createcommits, and an expired instance reloads itself lazily on the next attribute access, which cannot work under asyncio.sa_relationship_kwargs={"lazy": "selectin"}on any relationship a test reads back, for the same reason.
The factory commits once per create, so objects are visible to other
connections immediately. That is deliberate: a test that paginates or queries
through a second session sees the fixtures.
Compatibility
| Python | 3.10, 3.11, 3.12, 3.13 |
| factory_boy | >= 3 |
| SQLAlchemy | >= 2, async engine |
| SQLModel | >= 0.0.25 |
Licence
MIT. See LICENSE.
Metadata
Release files for sqlmodel-async-factory 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sqlmodel_async_factory-0.1.0.tar.gz | 5.0 kB | Without provenance | Details for sqlmodel_async_factory-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sqlmodel_async_factory-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for sqlmodel_async_factory-0.1.0-py3-none-any.whl |
Total release size: 11.3 kB
Release files / sqlmodel_async_factory-0.1.0.tar.gz
| Download URL | sqlmodel_async_factory-0.1.0.tar.gz |
|---|---|
| Size | 5.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a406b4b6ff049d30b07db2d2e4940aa3a6df92cd874277db31b097d87f28592d
|
|
BLAKE2b-256 checksum How to use checksums |
f053bea89a216601ffe34c65b3da13b67d64e77c2c7e72b61c35b7814ef52fb2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / sqlmodel_async_factory-0.1.0-py3-none-any.whl
| Download URL | sqlmodel_async_factory-0.1.0-py3-none-any.whl |
|---|---|
| Size | 6.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
54ab98f180d6991da14395d4e9ef777c796ed7410f72e838708f06f777cf5b53
|
|
BLAKE2b-256 checksum How to use checksums |
88a36ce86358d1b2d89842459d6e976c16bf96ffef31222e7959ba88403c6b09
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for sqlmodel-async-factory 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.