Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

django-pledge

Django models for pledge, a double-entry ledger inside PostgreSQL. Create accounts and transfers with the usual Django API; the database keeps the books straight.

Documentation · Source · Example app

Requires Python 3.11+, Django 4.2+, psycopg 3 and a PostgreSQL database with the pledge extension available.

Install

pip install django-pledge
INSTALLED_APPS = [
    # ...
    "django_pledge",  # app label "pledge"
]
python manage.py migrate pledge

The first migration runs CREATE EXTENSION IF NOT EXISTS pledge, which needs a superuser. If your app role isn't one, create the extension by hand and give the role the grants from the docs.

Usage

from decimal import Decimal

from django_pledge.models import Account, Transfer

cash = Account.objects.create(name="cash", currency="EUR")
alice = Account.objects.create(name="alice", currency="EUR", allow_negative_balance=False)

Transfer.objects.create(from_account=cash, to_account=alice, amount=Decimal("10.00"))
cash.transfer(alice, 5)  # the same, shorter

# one atomic batch, one statement
Transfer.objects.bulk_create(
    [
        Transfer(from_account=alice, to_account=cash, amount=Decimal("2.50")),
        Transfer(from_account=cash, to_account=alice, amount=1, metadata={"line": 2}),
    ]
)

alice.refresh_from_db()
alice.balance  # Decimal('13.50')
alice.history()  # entries with running balances, oldest first
alice.balance_at(some_datetime)
Transfer.objects.filter(from_account__name="cash", amount__gte=5)

Account.objects.assert_verified()  # raises if the ledger is inconsistent

Amounts are Decimal, int or a numeric string; float raises ValidationError. Writes run in transaction.atomic(), follow using() / db_manager() and database routers, and have async variants (acreate, abulk_create, asave).

Ledger rows are append-only: updating or deleting a stored row through the ORM raises ReadOnlyError. Accounts are closed with account.close() (needs a zero balance), never deleted.

Safe retries

Store a transfer id with your own record before you call the ledger, and send the same id when you retry. The same transfer twice is booked once; different values raise TransferConflict.

from django_pledge import TransferId

payment.transfer_id = TransferId.new()
payment.save()
cash.transfer(alice, payment.amount, id=payment.transfer_id)  # safe to retry

Linking your models

Point a ForeignKey or OneToOneField at pledge.Account with db_constraint=False (the target is a database view):

from django.db import models


class Wallet(models.Model):
    user = models.OneToOneField("auth.User", models.CASCADE)
    account = models.OneToOneField(
        "pledge.Account", models.PROTECT, db_constraint=False, related_name="wallet"
    )


Wallet.objects.filter(account__currency="EUR", account__balance__gt=0)

Proxy models of Account are fine for extra methods; multi-table inheritance is rejected.

Errors

Ledger rule violations raise subclasses of django_pledge.LedgerError, with the ids involved as typed attributes:

import django_pledge

try:
    cash.transfer(alice, amount)
except django_pledge.NegativeBalanceNotAllowed as e:
    e.account_id  # AccountId of the account that would go negative
except django_pledge.LedgerError as e:
    e.code, e.message

django_pledge.translate(exc) does the same for errors from raw SQL. All error classes are in the docs.

Also included

  • Typed ids: AccountId, TransferId, EntryId, and model fields for them.
  • django_pledge.admin.ReadOnlyAdmin to browse the ledger in the admin.
  • django_pledge.json.LedgerJSONEncoder, which writes Decimals in plain notation.

Development

From the repository root, start PostgreSQL with pledge (docker compose up -d --wait db), then in python/:

uv sync --all-groups
uv run pytest
uv run ruff check . && uv run --group lint ty check

License

MIT

Metadata

Release files for django-pledge 0.0.1a2

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-pledge 0.0.1a2
File Size Uploaded Provenance Actions
django_pledge-0.0.1a2.tar.gz 14.6 kB Without provenance Details for django_pledge-0.0.1a2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-pledge 0.0.1a2
File Interpreter ABI Platform Actions
django_pledge-0.0.1a2-py3-none-any.whl Python 3 none any Details for django_pledge-0.0.1a2-py3-none-any.whl

Total release size: 32.8 kB

Release files / django_pledge-0.0.1a2.tar.gz

Download URL django_pledge-0.0.1a2.tar.gz
Size 14.6 kB
Tags Source
SHA-256 checksum
How to use checksums
aad5dd40102a1125140edb5e520a3f5c2fb9c19653b6bf2e5d920a1c71c8acc9
BLAKE2b-256 checksum
How to use checksums
071a27f4838f76a83b171cd79738f417942e874e17ecd63437d5e0929b3b2d33
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / django_pledge-0.0.1a2-py3-none-any.whl

Download URL django_pledge-0.0.1a2-py3-none-any.whl
Size 18.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f79cbe81ff66ff6676e2b56f2b01f5edd0e7b77cf917086758ad8859d8f122a7
BLAKE2b-256 checksum
How to use checksums
587fecefb65f66ba20d22b83ae293503c821be959b6944bfee9fcb81ca8383fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for django-pledge 0.0.1a2

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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