Getting Started¶
Welcome to the Google Cloud Datastore ODM! This guide will walk you through installing the library, connecting to your database, and performing your first basic CRUD operations.
Installation¶
We recommend using uv or standard pip to install the library.
Define a Model¶
Models represent your Datastore entities. You define them by subclassing Model and declaring Property descriptors as class attributes.
Let's create a simple Task model:
from google_cloud_datastore_odm import Model, StringProperty, BooleanProperty, IntegerProperty
class Task(Model):
title = StringProperty(required=True)
description = StringProperty()
priority = IntegerProperty(default=1, choices=[1, 2, 3, 4, 5])
is_completed = BooleanProperty(default=False)
By default, the Datastore Kind will automatically match the name of your class (in this case, "Task").
Instantiate model and persist¶
The ODM automatically connects to Datastore using your environment's default credentials (like the GOOGLE_CLOUD_PROJECT variable). You don't need to manually pass connection objects around.
Let's create a task and save it:
# 1. Create an instance in memory
task = Task(title="Write Documentation", description="Draft the getting started guide.", priority=5)
# 2. Save it to Datastore (This automatically generates a unique ID!)
saved_key = task.put()
print(f"Task saved with ID: {saved_key.id_or_name}")
Want to specify your own ID instead of letting Datastore generate one? Just pass the id argument during creation:
Retrieve Data¶
You can fetch entities directly if you know their Key or their ID.
# Fetch by string or integer ID
fetched_task = Task.get_by_id("task-admin-123")
if fetched_task:
print(f"Found task: {fetched_task.title}")
# You can access properties via attributes...
print(f"Completed? {fetched_task.is_completed}")
# ...or like a dictionary!
print(f"Priority: {fetched_task['priority']}")
Update and Delete¶
Updating an entity is as simple as changing its properties in memory and calling .put() again.
To permanently remove the entity from Datastore:
Querying¶
The ODM features a powerful, Python-native query builder. Let's find all high-priority tasks that are not yet completed:
# 1. Build the query using standard Python operators
high_priority_query = Task.query().filter(
Task.priority >= 4,
Task.is_completed == False
)
# 2. Execute and iterate over the results
for open_task in high_priority_query.fetch():
print(f"URGENT: {open_task.title}")