Skip to main content

django-bulk-save

An efficiency utility for Django that aims to make bulk persistence easy when models require custom save logic.

Read the documentation, starting with installation and the usage guide. The API reference describes the context methods and custom exceptions.

Database support

Currently, PostgreSQL is the only supported database engine. Support for other database engines will be developed upon request. Please open an issue specifying the engine you need and your use case.

Motivation

Django's bulk_update() updates multiple model instances, but it does not call each model's save() method. This means that custom logic in an overridden save() method—including required application-level validations—is skipped.

Calling save() on every instance runs that logic, but typically issues a separate update query for each object. When updating many objects, those individual database queries can become a significant performance cost.

The library runs custom logic for each instance first, then persists updates with django-pgbulk on PostgreSQL. New instances use Django's bulk_create() so generated primary keys are populated. This keeps per-instance validation and preparation while reducing the number of database queries.

Quick start

From a local checkout, install with python -m pip install -e . and configure your Django project's default database to use PostgreSQL. Define a model in your installed Django app, then create and apply its migrations:

from django.db import models
from django_bulk_save import BulkSaveableModel


class Item(BulkSaveableModel):
    name = models.CharField(max_length=100)
    quantity = models.IntegerField(default=0)

    def before_save(self):
        self.name = self.name.strip()
        if not self.name:
            raise ValueError("Name must not be empty.")
  1. Collect the instances to save and the fields to update.
  2. Run each instance's custom validation and preparation logic.
  3. Persist the prepared changes in bulk.

Use a context to collect the writes:

Override before_save() for the logic to run in a bulk save. The context does not call save() or emit save signals, and regular save() calls do not automatically invoke before_save().

items = [Item(name=" first "), Item(name=" second ")]

with Item.bulk_save() as context:
    for item in items:
        context.register(item, update_fields=["name", "quantity"])

Hooks run before any queued writes. Creates and updates are committed in one transaction, with updates grouped by their update_fields. Updates exclusively use pgbulk.update() with its default ignore_unchanged=False; unchanged rows are still updated. Performance depends on the workload and should be measured on PostgreSQL.

For existing instances, list every field you want persisted, including fields modified by the hook. For creates, the field list does not restrict inserted columns. See the usage guide for update examples, transaction behavior, and current limitations, including assigned primary keys and database routing.

Error handling

The library exports BulkSaveError as the base class for its own errors:

  • InvalidInstanceError: a registered object is not an instance of the context's model.
  • InvalidUpdateFieldsError: field names are malformed, or an update requests an empty list, an unknown field, a primary key, a non-concrete field, a many-to-many field, or an auto_now_add field.

Errors raised by before_save(), the context body, and the database propagate unchanged, including Django's IntegrityError. Exceptions escaping the context roll back its transaction. The library does not print errors.

register() snapshots the supplied field names. The registry is cleared when the context exits, whether it succeeds or fails. To deliberately discard queued operations inside the context, use context.clear(). This replaces the former flush() method, which only discarded operations and did not persist them.

Documentation

The documentation uses standard reStructuredText so it can be read directly on GitHub. Sphinx adds navigation when building the HTML version. Build it from the repository root:

python -m pip install -e '.[docs]'
python -m sphinx -b html -W --keep-going docs docs/_build/html

Open docs/_build/html/index.html. No Django configuration or running database is needed to build the documentation.

Tests

Install the project and test dependencies with python -m pip install -e '.[test]'. The database tests require a dedicated PostgreSQL server and a database user with permission to create test databases:

PGHOST=localhost PGPORT=5432 \
PGDATABASE=bulk_save PGUSER=postgres PGPASSWORD=your_password \
python -m pytest

Project status

This project is an early prototype. PostgreSQL updates use django-pgbulk; the API is still under development.

Contributing

Contributions are very welcome! Whether you want to report a bug, suggest an idea, improve the documentation, or contribute code, you are encouraged to get involved at any experience level.

Please keep discussions friendly, polite, and respectful. Constructive feedback and different opinions are welcome, as long as everyone treats others with consideration.

See CONTRIBUTING.md for guidance on how to contribute.

Metadata

Release files for django-bulk-save 0.2.0

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-bulk-save 0.2.0
File Size Uploaded Provenance Actions
django_bulk_save-0.2.0.tar.gz 5.1 kB With provenance Details for django_bulk_save-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-bulk-save 0.2.0
File Interpreter ABI Platform Actions
django_bulk_save-0.2.0-py3-none-any.whl Python 3 none any Details for django_bulk_save-0.2.0-py3-none-any.whl

Total release size: 11.0 kB

Release files / django_bulk_save-0.2.0.tar.gz

Download URL django_bulk_save-0.2.0.tar.gz
Size 5.1 kB
Tags Source
SHA-256 checksum
How to use checksums
abe6383aad5686f89294f1644e2e6c522566553e07641630d98bf83b55df5978
BLAKE2b-256 checksum
How to use checksums
fa19526e378fdddaad0e067e6cdf52fae5a0635de0cde4d2989f33c1c6beea43
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Release files / django_bulk_save-0.2.0-py3-none-any.whl

Download URL django_bulk_save-0.2.0-py3-none-any.whl
Size 5.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a3cc5995cf2ae86b47571b756ad869150271f3c9322e3d86eb27eca7c86ea5ea
BLAKE2b-256 checksum
How to use checksums
c596cecbb9bdf98a35b156f6612aba46c2e5d0be1e5b326429cbdb1581118891
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 GitHub Actions, verified by PyPI on Oct 11, 2026.

Transparency log

Security for django-bulk-save 0.2.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.

Full provenance

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

Select from 2 files

Attestation for django_bulk_save-0.2.0.tar.gz

PyPI Publish Attestation

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

Signed by GitHub Actions, verified by PyPI on Oct 11, 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.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

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