Modelfire
Akif Patel
Published
0
[Modelfire](https://www.twine.net/signin
Modelfire is a lightweight, developer-friendly ORM for Google Cloud Firestore, built on top of Pydantic v2. It provides a clean, typed interface for document modeling, relationship management, and distributed locking. It’s somewhat inspired by the old App Engine Datastore ORM.
Features
- Pydantic Integration: Full power of Pydantic v2 for data validation and normalization.
- Pythonic UX: A clean, fluent API that makes Firestore feel like native Python code.
- Typed Queries: A
QueryProxythat returns instantiated model objects instead of raw dictionaries. - Sub-collections: Easy parent-child relationship modeling with
ChildCollection. - Updates: Use
.partialto update specific fields without overwriting the entire document. - Mutex: Simple Firestore-backed locking for multi-worker synchronization.
class User(FirestoreModel):
__collection__ = 'users'
username: str
posts = ChildCollection(Post)
# Create and save
user = User(username="johndoe")
user.save()
print(user.id)
Getting Started
1. Initialize
First, initialize Modelfire with a Firestore client or a specific document reference (for namespacing).
init_modelfire(firestore_client)
2. Define Models
Define your documents by inheriting from FirestoreModel.
from modelfire import FirestoreModel, ChildCollection
class Post(FirestoreModel):
__collection__ = 'posts'
title: str
content: str
class User(FirestoreModel):
__collection__ = 'users'
username: str
# Define a sub-collection
posts = ChildCollection(Post)
3. CRUD & Relationships
user = User.get_by_id(user_id)
print(user.username)
# Create a post in the user's sub-collection
post = user.posts.new(title="Hello World", content="My first post")
post.save()
# Query with auto-instantiation
recent_posts = user.posts.query().limit(10).stream()
for p in recent_posts:
print(p.title)
4. Updates (Partial)
Update only specific fields without fetching or overwriting the whole document.
# Only updates the 'title', preserves 'content' and other fields
update = Post.partial(id="some_post_id", title="New Title")
update.save()