Skip to main content

Cloud Spanner support for Django

GA pypi versions

Cloud Spanner is the world’s first fully managed relational database service to offer both strong consistency and horizontal scalability for mission-critical online transaction processing (OLTP) applications. With Cloud Spanner you enjoy all the traditional benefits of a relational database; but unlike any other relational database service, Cloud Spanner scales horizontally to hundreds or thousands of servers to handle the biggest transactional workloads.

Quick Start

In order to use this library, you first need to go through the following steps:

  1. Select or create a Cloud Platform project.

  2. Enable billing for your project.

  3. Enable the Google Cloud Spanner API.

  4. Setup Authentication.

This package provides a 3rd-party database backend for using Cloud Spanner with the Django ORM. It uses the Cloud Spanner Python client library under the hood.

Installation

Install this library in a virtualenv using pip. virtualenv is a tool to create isolated Python and Django environments. The basic problem it addresses is one of dependencies and versions, and indirectly permissions.

With virtualenv, it’s possible to install this library without needing system install permissions, and without clashing with the installed system dependencies.

Supported versions

The library supports Django 5.2 and Django 6.0. The minimum required Python version is 3.10.

pip3 install "django>=5.2,<6.1"

Installing the package

To install from PyPI:

pip3 install django-google-spanner

To install from source:

git clone git@github.com:googleapis/google-cloud-python.git
cd packages/django-google-spanner
pip3 install -e .

Creating a Cloud Spanner instance and database

If you don’t already have a Cloud Spanner database, or want to start from scratch for a new Django application, you can create a new instance and database using the Google Cloud SDK:

gcloud spanner instances create $INSTANCE --config=regional-us-central1 --description="New Django Instance" --nodes=1
gcloud spanner databases create $DB --instance $INSTANCE

Configuring settings.py

This package provides a Django application named django_spanner. To use the Cloud Spanner database backend, the application needs to installed and configured:

  • Add django_spanner as the first entry in INSTALLED_APPS:

    INSTALLED_APPS = [
        'django_spanner',
        ...
    ]
  • Edit the DATABASES setting to point to an existing Cloud Spanner database:

    DATABASES = {
        'default': {
            'ENGINE': 'django_spanner',
            'PROJECT': '$PROJECT',
            'INSTANCE': '$INSTANCE',
            'NAME': '$DATABASE',
        }
    }

Configuring primary key generation

The Spanner Django engine by default uses random int64 values that are generated by the client as primary key values. This default is applied to all databases that are configured, including databases that use a different engine than Spanner. You can disable this behavior with the RANDOM_ID_GENERATION_ENABLED setting:

DATABASES = {
    'default': {
        'ENGINE': 'django_spanner',
        'PROJECT': '$PROJECT',
        'INSTANCE': '$INSTANCE',
        'NAME': '$DATABASE',
        'RANDOM_ID_GENERATION_ENABLED': false,
    }
}

Transaction support in autocommit mode

Django supports transactions in autocommit mode by default. A transaction is automatically started if you define an atomic block.

To disable transactions in autocommit mode, set the flag ALLOW_TRANSACTIONS_IN_AUTO_COMMIT to False in your settings.py file.

Set credentials and project environment variables

You’ll need to download a service account JSON key file and point to it using an environment variable:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/keyfile.json
export GOOGLE_CLOUD_PROJECT=gcloud_project

Apply the migrations

Please run:

$ python3 manage.py migrate

That’ll take a while to run. After this you should be able to see the tables and indexes created in your Cloud Spanner console.

Create a Django admin user

First you’ll need to create a user who can login to the admin site. Run the following command:

$ python3 manage.py createsuperuser

which will then produce a prompt which will allow you to create your super user

Username: admin
Email address: admin@example.com
Password: **********
Password (again): **********
Superuser created successfully.

Login as admin

Now, run the server

python3 manage.py runserver

Then visit http://127.0.0.1:8000/admin/

Create and register your first model

Please follow the guides in https://docs.djangoproject.com/en/5.2/intro/tutorial02/#creating-models to create and register the model to the Django’s automatically-generated admin site.

How it works

Overall design

"Overall Design"

Internals

"Internals"

Executing a query

Here is an example of how to add a row for Model Author, save it and later query it using Django

>>> author_kent = Author( first_name="Arthur", last_name="Kent", rating=Decimal("4.1"),)
>>> author_kent.save()
>>> qs1 = Author.objects.all().values("first_name", "last_name")

How to contribute

Contributions to this library are always welcome and highly encouraged.

See CONTRIBUTING for more information on how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See the Code of Conduct for more information.

DML RETURNING Behavior

Starting with Django 6.0 compatibility, can_return_columns_from_insert = True is enabled. Django will generate THEN RETURN clauses for insert statements that create model instances with database-generated defaults or GeneratedField columns.

If your application relies on the previous behavior (where returned columns were not queried automatically upon insert), you can disable it in your Django AppConfig:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = "myapp"

    def ready(self):
        from django_spanner.features import DatabaseFeatures

        DatabaseFeatures.can_return_columns_from_insert = False

Limitations

Spanner has certain limitations of its own. The full set of limitations is documented here. It is recommended that you go through that list.

Django spanner has a set of limitations as well, which you can find here.

Features from spanner that are not supported in Django-spanner are listed here.

Metadata

Release files for django-google-spanner 5.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-google-spanner 5.2.1
File Size Uploaded Provenance Actions
django_google_spanner-5.2.1.tar.gz 88.6 kB With provenance Details for django_google_spanner-5.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-google-spanner 5.2.1
File Interpreter ABI Platform Actions
django_google_spanner-5.2.1-py3-none-any.whl Python 3 none any Details for django_google_spanner-5.2.1-py3-none-any.whl

Total release size: 148.7 kB

Release files / django_google_spanner-5.2.1.tar.gz

Download URL django_google_spanner-5.2.1.tar.gz
Size 88.6 kB
Tags Source
SHA-256 checksum
How to use checksums
3291fdd289bc3a80b0bed4b5b5d5ff112dcb58075519f762da9d9533f50594af
BLAKE2b-256 checksum
How to use checksums
69a8f19c2ba21d541ff25fe3fe96403c87d11d088fccfcc362dd002e970aa013
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.2.0 CPython/3.11.2

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by Google Cloud, verified by PyPI on Nov 12, 2026.

Transparency log

Release files / django_google_spanner-5.2.1-py3-none-any.whl

Download URL django_google_spanner-5.2.1-py3-none-any.whl
Size 60.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
159cd090a93844287b50c04f43020711df4f8ef135b94646a4cb3a35cbfa0e8a
BLAKE2b-256 checksum
How to use checksums
eef1e51d215e402d5bd2f59be93e8ff6ed26ae1a841c54335f5e89c1b9b1594d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.2.0 CPython/3.11.2

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by Google Cloud, verified by PyPI on Nov 12, 2026.

Transparency log

Security for django-google-spanner 5.2.1

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_google_spanner-5.2.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by Google Cloud, verified by PyPI on Nov 12, 2026.

Transparency log

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page
⌂ 换网址