Skip to main content

Hook-style hooks for Django bulk operations like bulk_create and bulk_update.

Project description

django-bulk-hooks

⚡ Bulk hooks for Django bulk operations and individual model lifecycle events.

django-bulk-hooks brings a declarative, hook-like experience to Django's bulk_create, bulk_update, and bulk_delete — including support for BEFORE_ and AFTER_ hooks, conditions, batching, and transactional safety. It also provides comprehensive lifecycle hooks for individual model operations.

✨ Features

  • Declarative hook system: @hook(AFTER_UPDATE, condition=...)
  • BEFORE/AFTER hooks for create, update, delete
  • Hook-aware manager that wraps Django's bulk_ operations
  • NEW: HookModelMixin for individual model lifecycle events
  • Hook chaining, hook deduplication, and atomicity
  • Class-based hook handlers with DI support
  • Support for both bulk and individual model operations

🚀 Quickstart

pip install django-bulk-hooks

Define Your Model

from django.db import models
from django_bulk_hooks.models import HookModelMixin

class Account(HookModelMixin):
    balance = models.DecimalField(max_digits=10, decimal_places=2)
    # The HookModelMixin automatically provides BulkHookManager

Create a Hook Handler

from django_bulk_hooks import hook, AFTER_UPDATE, Hook
from django_bulk_hooks.conditions import WhenFieldHasChanged
from .models import Account

class AccountHooks(Hook):
    @hook(AFTER_UPDATE, model=Account, condition=WhenFieldHasChanged("balance"))
    def log_balance_change(self, new_records, old_records):
        print("Accounts updated:", [a.pk for a in new_records])
    
    @hook(BEFORE_CREATE, model=Account)
    def before_create(self, new_records, old_records):
        for account in new_records:
            if account.balance < 0:
                raise ValueError("Account cannot have negative balance")
    
    @hook(AFTER_DELETE, model=Account)
    def after_delete(self, new_records, old_records):
        print("Accounts deleted:", [a.pk for a in old_records])

🛠 Supported Hook Events

  • BEFORE_CREATE, AFTER_CREATE
  • BEFORE_UPDATE, AFTER_UPDATE
  • BEFORE_DELETE, AFTER_DELETE

🔄 Lifecycle Events

Individual Model Operations

The HookModelMixin automatically triggers hooks for individual model operations:

# These will trigger BEFORE_CREATE and AFTER_CREATE hooks
account = Account.objects.create(balance=100.00)
account.save()  # for new instances

# These will trigger BEFORE_UPDATE and AFTER_UPDATE hooks
account.balance = 200.00
account.save()  # for existing instances

# This will trigger BEFORE_DELETE and AFTER_DELETE hooks
account.delete()

Bulk Operations

Bulk operations also trigger the same hooks:

# Bulk create - triggers BEFORE_CREATE and AFTER_CREATE hooks
accounts = [
    Account(balance=100.00),
    Account(balance=200.00),
]
Account.objects.bulk_create(accounts)

# Bulk update - triggers BEFORE_UPDATE and AFTER_UPDATE hooks
for account in accounts:
    account.balance *= 1.1
Account.objects.bulk_update(accounts, ['balance'])

# Bulk delete - triggers BEFORE_DELETE and AFTER_DELETE hooks
Account.objects.bulk_delete(accounts)

Queryset Operations

Queryset operations are also supported:

# Queryset update - triggers BEFORE_UPDATE and AFTER_UPDATE hooks
Account.objects.update(balance=0.00)

# Queryset delete - triggers BEFORE_DELETE and AFTER_DELETE hooks
Account.objects.delete()

🧠 Why?

Django's bulk_ methods bypass signals and save(). This package fills that gap with:

  • Hooks that behave consistently across creates/updates/deletes
  • NEW: Individual model lifecycle hooks that work with save() and delete()
  • Scalable performance via chunking (default 200)
  • Support for @hook decorators and centralized hook classes
  • NEW: Automatic hook triggering for admin operations and other Django features

📦 Usage Examples

Individual Model Operations

# These automatically trigger hooks
account = Account.objects.create(balance=100.00)
account.balance = 200.00
account.save()
account.delete()

Bulk Operations

# These also trigger hooks
Account.objects.bulk_create(accounts)
Account.objects.bulk_update(accounts, ['balance'])
Account.objects.bulk_delete(accounts)

Advanced Hook Usage

class AdvancedAccountHooks(Hook):
    @hook(BEFORE_UPDATE, model=Account, condition=WhenFieldHasChanged("balance"))
    def validate_balance_change(self, new_records, old_records):
        for new_account, old_account in zip(new_records, old_records):
            if new_account.balance < 0 and old_account.balance >= 0:
                raise ValueError("Cannot set negative balance")
    
    @hook(AFTER_CREATE, model=Account)
    def send_welcome_email(self, new_records, old_records):
        for account in new_records:
            # Send welcome email logic here
            pass

🧩 Integration with Queryable Properties

You can extend from BulkHookManager to support formula fields or property querying.

class MyManager(BulkHookManager, QueryablePropertiesManager):
    pass

📝 License

MIT © 2024 Augend / Konrad Beck

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_bulk_hooks-0.1.70.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_bulk_hooks-0.1.70-py3-none-any.whl (14.2 kB view details)

Uploaded Python 3

File details

Details for the file django_bulk_hooks-0.1.70.tar.gz.

File metadata

  • Download URL: django_bulk_hooks-0.1.70.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.11.9 Windows/10

File hashes

Hashes for django_bulk_hooks-0.1.70.tar.gz
Algorithm Hash digest
SHA256 f66aebc189621710e9cf0cec70a0ceaa459f49f2b976686c29276c36d83af262
MD5 e2d1e9547f1a2a95f87aefba6681bce4
BLAKE2b-256 4152ef46f21cef01c043b84c19b6c811593609444be9bbf71b1a6e4b8f5c3db7

See more details on using hashes here.

File details

Details for the file django_bulk_hooks-0.1.70-py3-none-any.whl.

File metadata

File hashes

Hashes for django_bulk_hooks-0.1.70-py3-none-any.whl
Algorithm Hash digest
SHA256 6cb758b29f9e4fb98cd6a9897312873738c17f0b0d82954c7ecc34a1440cb929
MD5 a041db5a4387b87caafa6f8b904a3d82
BLAKE2b-256 53d82597cdb09d1e0b137be31563b9059e75a45e8b034e9c49d5685c122fc5f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page