BaseFirestoreModel is the foundation of the Firestore Pydantic ODM. Every document model in your application inherits from it, gaining a complete async CRUD interface — including filtering, pagination, batch operations, and subcollection traversal — while remaining a fully valid Pydantic model for serialization and validation.
Class overview
BaseFirestoreModel extends Pydantic BaseModel and adds Firestore-aware behaviour through class-level injection of a FirestoreDB instance. All database operations are async and must be awaited (or iterated with async for in the case of generators). The class is compatible with both Pydantic v1 and v2.
The Settings inner class
Each model should define an inner Settings class to control how it maps to Firestore.
| Attribute | Type | Description |
|---|---|---|
name | str | The Firestore collection name. Defaults to "BaseCollection" on the base class — always override this in subclasses. |
parent | Type[BaseFirestoreModel] | Set on subcollection models to declare the parent document type. Omit for top-level collections. |
The id field
id field. When id is None at save time, Firestore auto-generates one. The field is excluded from serialised document data — it is stored only as the document key.
Class methods
initialize_db
Inject the FirestoreDB instance that all operations on this class will use. Called automatically by init_firestore_odm — you rarely need to call it directly.
The
FirestoreDB wrapper instance containing the underlying AsyncClient.initialize_fields
Attach FirestoreField descriptors to every Pydantic field on the class so that filter expressions like User.email == "[email protected]" produce the correct Firestore FieldFilter tuples. Called automatically by init_firestore_odm.
After
initialize_fields runs, accessing a class attribute such as User.email returns a FirestoreField object that supports ==, !=, <, <=, >, >=, in, and array_contains operators to build filter tuples.get
Retrieve a single document by its Firestore document ID.
The Firestore document ID to look up.
Parent document instance required when this model is a subcollection. Omit for top-level collections.
None if no document with that ID exists.
exists
Return True if a document with the given ID exists in Firestore, without fetching its data.
The Firestore document ID to check.
Parent document instance for subcollection models.
find
Asynchronously stream documents matching the given filters. Returns an AsyncGenerator — iterate with async for.
A list of filter tuples. Each tuple is
(field, operator, value). Build tuples with FirestoreField expressions such as User.email == "[email protected]" or raw strings ("email", "==", "[email protected]"). Defaults to [] (no filters — returns all documents).Parent document instance for subcollection models.
A Pydantic model class containing only the fields you want retrieved. Reduces bandwidth by using Firestore field projection.
A field or list of fields to sort by. Pass a
(field, OrderByDirection) tuple for explicit direction, or just a field for the default ascending order.Maximum number of documents to return.
Number of documents to skip before returning results.
find_one
Return the first document matching the given filters, or None if no match is found. Internally calls find(..., limit=1).
Filter tuples identical to those accepted by
find.Parent document instance for subcollection models.
Optional Pydantic model class for field projection.
Field to sort by to determine which document is “first”.
count
Return the number of documents that match the given filters using Firestore’s native count() aggregation. Falls back to fetching all document IDs if the SDK version does not support count().
Filter tuples. Pass an empty list
[] to count all documents in the collection.Parent document instance for subcollection models.
batch_write
Execute multiple create, update, and delete operations atomically in a single Firestore batch commit.
A list of
(BatchOperation, model_instance) tuples. BatchOperation is an enum with values CREATE, UPDATE, and DELETE. The model instances do not need to belong to the same collection — the collection is inferred from each instance’s class.collection_group_find
Query across all subcollections sharing this model’s collection name, regardless of which parent document they belong to. Uses Firestore’s collection_group() API.
Filter tuples applied across all matching subcollections. Defaults to
[].Optional Pydantic model class for field projection.
Field(s) to sort results by.
Maximum number of documents to return across all parents.
Number of matching documents to skip.
Collection group queries require a Firestore composite index. The
_parent_path attribute is automatically populated on each returned instance from the document’s reference path.Instance methods
save
Persist a new document to Firestore. If id is None, Firestore generates a unique document ID and assigns it to the instance. Raises RuntimeError if the database has not been initialised, or if an explicit id is provided but a document with that ID already exists.
Parent document instance. Required for subcollection models if
_parent_path is not already stored on the instance.When
True, fields with None values are not written to Firestore.When
True, field aliases are used as Firestore field names in the document.When
True, fields that were not explicitly set during model construction are omitted from the write.id populated.
update
Update fields on an existing Firestore document. The instance must have a non-None id — raises ValueError if id is not set. Only fields that pass the exclusion rules are sent to Firestore.
Parent document instance for subcollection models.
An explicit set of field names to include in the update. When provided, only those fields are written — all other exclusion rules still apply within the included set.
Omit fields whose value is
None.Use field aliases as Firestore field names.
Omit fields that were not explicitly set on the instance.
delete
Delete the document from Firestore. The instance must have a non-None id — raises ValueError if id is not set.
When
True, all subcollection documents under this document are recursively deleted before the document itself is removed. Requires subcollection model classes to be registered via init_firestore_odm.subcollection
Return a SubCollectionAccessor bound to this instance and the given child model class, enabling Beanie-style subcollection query syntax.
The subcollection model class. Must declare
Settings.parent = type(self) or a ValueError is raised.SubCollectionAccessor reference for the full accessor API.
Properties
collection_name
Return the Firestore collection name for the instance’s class, as declared in Settings.name. Falls back to the class name if Settings.name is not defined.
get_collection_name
Class-level counterpart to the collection_name property. Returns the same value but can be called on the class itself without an instance — useful inside other classmethods and internal path resolution helpers.
