django-bulk-hooks 0.1.101__py3-none-any.whl → 0.1.102__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_bulk_hooks/__init__.py +11 -23
- django_bulk_hooks/conditions.py +185 -167
- django_bulk_hooks/decorators.py +112 -7
- django_bulk_hooks/engine.py +15 -82
- django_bulk_hooks/handler.py +3 -28
- django_bulk_hooks/manager.py +69 -31
- django_bulk_hooks/models.py +14 -33
- django_bulk_hooks/registry.py +3 -3
- django_bulk_hooks-0.1.102.dist-info/METADATA +228 -0
- django_bulk_hooks-0.1.102.dist-info/RECORD +16 -0
- django_bulk_hooks-0.1.101.dist-info/METADATA +0 -295
- django_bulk_hooks-0.1.101.dist-info/RECORD +0 -16
- {django_bulk_hooks-0.1.101.dist-info → django_bulk_hooks-0.1.102.dist-info}/LICENSE +0 -0
- {django_bulk_hooks-0.1.101.dist-info → django_bulk_hooks-0.1.102.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: django-bulk-hooks
|
|
3
|
+
Version: 0.1.102
|
|
4
|
+
Summary: Hook-style hooks for Django bulk operations like bulk_create and bulk_update.
|
|
5
|
+
Home-page: https://github.com/AugendLimited/django-bulk-hooks
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: django,bulk,hooks
|
|
8
|
+
Author: Konrad Beck
|
|
9
|
+
Author-email: konrad.beck@merchantcapital.co.za
|
|
10
|
+
Requires-Python: >=3.11,<4.0
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Dist: Django (>=4.0)
|
|
17
|
+
Project-URL: Repository, https://github.com/AugendLimited/django-bulk-hooks
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# django-bulk-hooks
|
|
22
|
+
|
|
23
|
+
⚡ Bulk hooks for Django bulk operations and individual model lifecycle events.
|
|
24
|
+
|
|
25
|
+
`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.
|
|
26
|
+
|
|
27
|
+
## ✨ Features
|
|
28
|
+
|
|
29
|
+
- Declarative hook system: `@hook(AFTER_UPDATE, condition=...)`
|
|
30
|
+
- BEFORE/AFTER hooks for create, update, delete
|
|
31
|
+
- Hook-aware manager that wraps Django's `bulk_` operations
|
|
32
|
+
- **NEW**: `HookModelMixin` for individual model lifecycle events
|
|
33
|
+
- Hook chaining, hook deduplication, and atomicity
|
|
34
|
+
- Class-based hook handlers with DI support
|
|
35
|
+
- Support for both bulk and individual model operations
|
|
36
|
+
- **NEW**: Safe handling of related objects to prevent `RelatedObjectDoesNotExist` errors
|
|
37
|
+
|
|
38
|
+
## 🚀 Quickstart
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install django-bulk-hooks
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Define Your Model
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from django.db import models
|
|
48
|
+
from django_bulk_hooks.models import HookModelMixin
|
|
49
|
+
|
|
50
|
+
class Account(HookModelMixin):
|
|
51
|
+
balance = models.DecimalField(max_digits=10, decimal_places=2)
|
|
52
|
+
# The HookModelMixin automatically provides BulkHookManager
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Create a Hook Handler
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from django_bulk_hooks import hook, AFTER_UPDATE, Hook
|
|
59
|
+
from django_bulk_hooks.conditions import WhenFieldHasChanged
|
|
60
|
+
from .models import Account
|
|
61
|
+
|
|
62
|
+
class AccountHooks(HookHandler):
|
|
63
|
+
@hook(AFTER_UPDATE, model=Account, condition=WhenFieldHasChanged("balance"))
|
|
64
|
+
def log_balance_change(self, new_records, old_records):
|
|
65
|
+
print("Accounts updated:", [a.pk for a in new_records])
|
|
66
|
+
|
|
67
|
+
@hook(BEFORE_CREATE, model=Account)
|
|
68
|
+
def before_create(self, new_records, old_records):
|
|
69
|
+
for account in new_records:
|
|
70
|
+
if account.balance < 0:
|
|
71
|
+
raise ValueError("Account cannot have negative balance")
|
|
72
|
+
|
|
73
|
+
@hook(AFTER_DELETE, model=Account)
|
|
74
|
+
def after_delete(self, new_records, old_records):
|
|
75
|
+
print("Accounts deleted:", [a.pk for a in old_records])
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Advanced Hook Usage
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
class AdvancedAccountHooks(HookHandler):
|
|
82
|
+
@hook(BEFORE_UPDATE, model=Account, condition=WhenFieldHasChanged("balance"))
|
|
83
|
+
def validate_balance_change(self, new_records, old_records):
|
|
84
|
+
for new_account, old_account in zip(new_records, old_records):
|
|
85
|
+
if new_account.balance < 0 and old_account.balance >= 0:
|
|
86
|
+
raise ValueError("Cannot set negative balance")
|
|
87
|
+
|
|
88
|
+
@hook(AFTER_CREATE, model=Account)
|
|
89
|
+
def send_welcome_email(self, new_records, old_records):
|
|
90
|
+
for account in new_records:
|
|
91
|
+
# Send welcome email logic here
|
|
92
|
+
pass
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## 🔒 Safely Handling Related Objects
|
|
96
|
+
|
|
97
|
+
One of the most common issues when working with hooks is the `RelatedObjectDoesNotExist` exception. This occurs when you try to access a related object that doesn't exist or hasn't been saved yet.
|
|
98
|
+
|
|
99
|
+
### The Problem
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
# ❌ DANGEROUS: This can raise RelatedObjectDoesNotExist
|
|
103
|
+
@hook(AFTER_CREATE, model=Transaction)
|
|
104
|
+
def process_transaction(self, new_records, old_records):
|
|
105
|
+
for transaction in new_records:
|
|
106
|
+
# This will fail if transaction.status is None or doesn't exist
|
|
107
|
+
if transaction.status.name == "COMPLETE":
|
|
108
|
+
# Process the transaction
|
|
109
|
+
pass
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### The Solution
|
|
113
|
+
|
|
114
|
+
Use the `safe_get_related_attr` utility function to safely access related object attributes:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from django_bulk_hooks.conditions import safe_get_related_attr
|
|
118
|
+
|
|
119
|
+
# ✅ SAFE: Use safe_get_related_attr to handle None values
|
|
120
|
+
@hook(AFTER_CREATE, model=Transaction)
|
|
121
|
+
def process_transaction(self, new_records, old_records):
|
|
122
|
+
for transaction in new_records:
|
|
123
|
+
# Safely get the status name, returns None if status doesn't exist
|
|
124
|
+
status_name = safe_get_related_attr(transaction, 'status', 'name')
|
|
125
|
+
|
|
126
|
+
if status_name == "COMPLETE":
|
|
127
|
+
# Process the transaction
|
|
128
|
+
pass
|
|
129
|
+
elif status_name is None:
|
|
130
|
+
# Handle case where status is not set
|
|
131
|
+
print(f"Transaction {transaction.id} has no status")
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Complete Example
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from django.db import models
|
|
138
|
+
from django_bulk_hooks import hook
|
|
139
|
+
from django_bulk_hooks.conditions import safe_get_related_attr
|
|
140
|
+
|
|
141
|
+
class Status(models.Model):
|
|
142
|
+
name = models.CharField(max_length=50)
|
|
143
|
+
|
|
144
|
+
class Transaction(HookModelMixin, models.Model):
|
|
145
|
+
amount = models.DecimalField(max_digits=10, decimal_places=2)
|
|
146
|
+
status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)
|
|
147
|
+
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True)
|
|
148
|
+
|
|
149
|
+
class TransactionHandler:
|
|
150
|
+
@hook(Transaction, "before_create")
|
|
151
|
+
def set_default_status(self, new_records, old_records=None):
|
|
152
|
+
"""Set default status for new transactions."""
|
|
153
|
+
default_status = Status.objects.filter(name="PENDING").first()
|
|
154
|
+
for transaction in new_records:
|
|
155
|
+
if transaction.status is None:
|
|
156
|
+
transaction.status = default_status
|
|
157
|
+
|
|
158
|
+
@hook(Transaction, "after_create")
|
|
159
|
+
def process_transactions(self, new_records, old_records=None):
|
|
160
|
+
"""Process transactions based on their status."""
|
|
161
|
+
for transaction in new_records:
|
|
162
|
+
# ✅ SAFE: Get status name safely
|
|
163
|
+
status_name = safe_get_related_attr(transaction, 'status', 'name')
|
|
164
|
+
|
|
165
|
+
if status_name == "COMPLETE":
|
|
166
|
+
self._process_complete_transaction(transaction)
|
|
167
|
+
elif status_name == "FAILED":
|
|
168
|
+
self._process_failed_transaction(transaction)
|
|
169
|
+
elif status_name is None:
|
|
170
|
+
print(f"Transaction {transaction.id} has no status")
|
|
171
|
+
|
|
172
|
+
# ✅ SAFE: Check for related object existence
|
|
173
|
+
category = safe_get_related_attr(transaction, 'category')
|
|
174
|
+
if category:
|
|
175
|
+
print(f"Transaction {transaction.id} belongs to category: {category.name}")
|
|
176
|
+
|
|
177
|
+
def _process_complete_transaction(self, transaction):
|
|
178
|
+
# Process complete transaction logic
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
def _process_failed_transaction(self, transaction):
|
|
182
|
+
# Process failed transaction logic
|
|
183
|
+
pass
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Best Practices for Related Objects
|
|
187
|
+
|
|
188
|
+
1. **Always use `safe_get_related_attr`** when accessing related object attributes in hooks
|
|
189
|
+
2. **Set default values in `BEFORE_CREATE` hooks** to ensure related objects exist
|
|
190
|
+
3. **Handle None cases explicitly** to avoid unexpected behavior
|
|
191
|
+
4. **Use bulk operations efficiently** by fetching related objects once and reusing them
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
class EfficientTransactionHandler:
|
|
195
|
+
@hook(Transaction, "before_create")
|
|
196
|
+
def prepare_transactions(self, new_records, old_records=None):
|
|
197
|
+
"""Efficiently prepare transactions for bulk creation."""
|
|
198
|
+
# Get default objects once to avoid multiple queries
|
|
199
|
+
default_status = Status.objects.filter(name="PENDING").first()
|
|
200
|
+
default_category = Category.objects.filter(name="GENERAL").first()
|
|
201
|
+
|
|
202
|
+
for transaction in new_records:
|
|
203
|
+
if transaction.status is None:
|
|
204
|
+
transaction.status = default_status
|
|
205
|
+
if transaction.category is None:
|
|
206
|
+
transaction.category = default_category
|
|
207
|
+
|
|
208
|
+
@hook(Transaction, "after_create")
|
|
209
|
+
def post_creation_processing(self, new_records, old_records=None):
|
|
210
|
+
"""Process transactions after creation."""
|
|
211
|
+
# Group by status for efficient processing
|
|
212
|
+
transactions_by_status = {}
|
|
213
|
+
|
|
214
|
+
for transaction in new_records:
|
|
215
|
+
status_name = safe_get_related_attr(transaction, 'status', 'name')
|
|
216
|
+
if status_name not in transactions_by_status:
|
|
217
|
+
transactions_by_status[status_name] = []
|
|
218
|
+
transactions_by_status[status_name].append(transaction)
|
|
219
|
+
|
|
220
|
+
# Process each group
|
|
221
|
+
for status_name, transactions in transactions_by_status.items():
|
|
222
|
+
if status_name == "COMPLETE":
|
|
223
|
+
self._batch_process_complete(transactions)
|
|
224
|
+
elif status_name == "FAILED":
|
|
225
|
+
self._batch_process_failed(transactions)
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
This approach ensures your hooks are robust and won't fail due to missing related objects, while also being efficient with database queries.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
django_bulk_hooks/__init__.py,sha256=b5LIO5oWX9ZVITZddma_E_Hosx8Zy9B3_v3z8HmSykg,1132
|
|
2
|
+
django_bulk_hooks/conditions.py,sha256=iCdIrpVciGsmyKgIEjcC0nl_2-mAxay4Tss-ZaenSuY,13735
|
|
3
|
+
django_bulk_hooks/constants.py,sha256=3x1H1fSUUNo0DZONN7GUVDuySZctTR-jtByBHmAIX5w,303
|
|
4
|
+
django_bulk_hooks/context.py,sha256=HVDT73uSzvgrOR6mdXTvsBm3hLOgBU8ant_mB7VlFuM,380
|
|
5
|
+
django_bulk_hooks/decorators.py,sha256=zstmb27dKcOHu3Atg7cauewCTzPvUmq03mzVKJRi56o,7230
|
|
6
|
+
django_bulk_hooks/engine.py,sha256=kWxAggInO8GhmQfSzJrGATAPgnuG7580llpO9NoxHA8,2897
|
|
7
|
+
django_bulk_hooks/enums.py,sha256=Zo8_tJzuzZ2IKfVc7gZ-0tWPT8q1QhqZbAyoh9ZVJbs,381
|
|
8
|
+
django_bulk_hooks/handler.py,sha256=Qpg_zT6SsQiTlhduvzXxPdG6uynjyR2fBjj-R6HZiXI,4861
|
|
9
|
+
django_bulk_hooks/manager.py,sha256=vyIc7ktNbjXCJrqP7SO7lsamBYFrZSCIQBmXSnpK874,12481
|
|
10
|
+
django_bulk_hooks/models.py,sha256=9KvWkmrR0wbTHN6r7-FrSSO9ViS83NvG7iXLBw_iDZs,4793
|
|
11
|
+
django_bulk_hooks/queryset.py,sha256=7lLqhZ-XOYsZ1I3Loxi4Nhz79M8HlTYE413AW8nyeDI,1330
|
|
12
|
+
django_bulk_hooks/registry.py,sha256=Vh78exKYcdZhM27120kQm-iXGOjd_kf9ZUYBZ8eQ2V0,683
|
|
13
|
+
django_bulk_hooks-0.1.102.dist-info/LICENSE,sha256=dguKIcbDGeZD-vXWdLyErPUALYOvtX_fO4Zjhq481uk,1088
|
|
14
|
+
django_bulk_hooks-0.1.102.dist-info/METADATA,sha256=xpdCGrDTHoLswDQAXL67JvvvUkyEyTkyQfdbRGDiuz8,9040
|
|
15
|
+
django_bulk_hooks-0.1.102.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
|
16
|
+
django_bulk_hooks-0.1.102.dist-info/RECORD,,
|
|
@@ -1,295 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: django-bulk-hooks
|
|
3
|
-
Version: 0.1.101
|
|
4
|
-
Summary: Hook-style hooks for Django bulk operations like bulk_create and bulk_update.
|
|
5
|
-
Home-page: https://github.com/AugendLimited/django-bulk-hooks
|
|
6
|
-
License: MIT
|
|
7
|
-
Keywords: django,bulk,hooks
|
|
8
|
-
Author: Konrad Beck
|
|
9
|
-
Author-email: konrad.beck@merchantcapital.co.za
|
|
10
|
-
Requires-Python: >=3.11,<4.0
|
|
11
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
-
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
-
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
-
Requires-Dist: Django (>=4.0)
|
|
17
|
-
Project-URL: Repository, https://github.com/AugendLimited/django-bulk-hooks
|
|
18
|
-
Description-Content-Type: text/markdown
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
# django-bulk-hooks
|
|
22
|
-
|
|
23
|
-
⚡ Bulk hooks for Django bulk operations and individual model lifecycle events.
|
|
24
|
-
|
|
25
|
-
`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.
|
|
26
|
-
|
|
27
|
-
## ✨ Features
|
|
28
|
-
|
|
29
|
-
- Declarative hook system: `@hook(AFTER_UPDATE, condition=...)`
|
|
30
|
-
- BEFORE/AFTER hooks for create, update, delete
|
|
31
|
-
- Hook-aware manager that wraps Django's `bulk_` operations
|
|
32
|
-
- **NEW**: `HookModelMixin` for individual model lifecycle events
|
|
33
|
-
- Hook chaining, hook deduplication, and atomicity
|
|
34
|
-
- Class-based hook handlers with DI support
|
|
35
|
-
- Support for both bulk and individual model operations
|
|
36
|
-
- **NEW**: Safe handling of related objects to prevent `RelatedObjectDoesNotExist` errors
|
|
37
|
-
- **NEW**: `@select_related` decorator to prevent queries in loops
|
|
38
|
-
|
|
39
|
-
## 🚀 Quickstart
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
pip install django-bulk-hooks
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
### Define Your Model
|
|
46
|
-
|
|
47
|
-
```python
|
|
48
|
-
from django.db import models
|
|
49
|
-
from django_bulk_hooks.models import HookModelMixin
|
|
50
|
-
|
|
51
|
-
class Account(HookModelMixin):
|
|
52
|
-
balance = models.DecimalField(max_digits=10, decimal_places=2)
|
|
53
|
-
# The HookModelMixin automatically provides BulkHookManager
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
### Create a Hook Handler
|
|
57
|
-
|
|
58
|
-
```python
|
|
59
|
-
from django_bulk_hooks import hook, AFTER_UPDATE, select_related
|
|
60
|
-
from django_bulk_hooks.conditions import WhenFieldHasChanged
|
|
61
|
-
from .models import Account
|
|
62
|
-
|
|
63
|
-
class AccountHandler:
|
|
64
|
-
@hook(AFTER_UPDATE, model=Account, condition=WhenFieldHasChanged("balance"))
|
|
65
|
-
@select_related("user") # Preload user to prevent queries in loops
|
|
66
|
-
def notify_balance_change(self, new_records, old_records):
|
|
67
|
-
for account in new_records:
|
|
68
|
-
# This won't cause a query since user is preloaded
|
|
69
|
-
user_email = account.user.email
|
|
70
|
-
self.send_notification(user_email, account.balance)
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
## 🔧 Using `@select_related` to Prevent Queries in Loops
|
|
74
|
-
|
|
75
|
-
The `@select_related` decorator is essential when your hook logic needs to access related objects. Without it, you might end up with N+1 query problems.
|
|
76
|
-
|
|
77
|
-
### ❌ Without `@select_related` (causes queries in loops)
|
|
78
|
-
|
|
79
|
-
```python
|
|
80
|
-
@hook(AFTER_CREATE, model=LoanAccount)
|
|
81
|
-
def process_accounts(self, new_records, old_records):
|
|
82
|
-
for account in new_records:
|
|
83
|
-
# ❌ This causes a query for each account!
|
|
84
|
-
status_name = account.status.name
|
|
85
|
-
if status_name == "ACTIVE":
|
|
86
|
-
self.activate_account(account)
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
### ✅ With `@select_related` (bulk loads related objects)
|
|
90
|
-
|
|
91
|
-
```python
|
|
92
|
-
@hook(AFTER_CREATE, model=LoanAccount)
|
|
93
|
-
@select_related("status") # Bulk load status objects
|
|
94
|
-
def process_accounts(self, new_records, old_records):
|
|
95
|
-
for account in new_records:
|
|
96
|
-
# ✅ No query here - status is preloaded
|
|
97
|
-
status_name = account.status.name
|
|
98
|
-
if status_name == "ACTIVE":
|
|
99
|
-
self.activate_account(account)
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
### Multiple Related Fields
|
|
103
|
-
|
|
104
|
-
```python
|
|
105
|
-
@hook(AFTER_UPDATE, model=Transaction)
|
|
106
|
-
@select_related("account", "category", "status")
|
|
107
|
-
def process_transactions(self, new_records, old_records):
|
|
108
|
-
for transaction in new_records:
|
|
109
|
-
# All related objects are preloaded - no queries in loops
|
|
110
|
-
account_name = transaction.account.name
|
|
111
|
-
category_type = transaction.category.type
|
|
112
|
-
status_name = transaction.status.name
|
|
113
|
-
|
|
114
|
-
if status_name == "COMPLETE":
|
|
115
|
-
self.process_complete_transaction(transaction)
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
### Your Original Example (Fixed)
|
|
119
|
-
|
|
120
|
-
```python
|
|
121
|
-
@hook(BEFORE_CREATE, model=LoanAccount, condition=IsEqual("status.name", value=Status.ACTIVE.value))
|
|
122
|
-
@hook(
|
|
123
|
-
BEFORE_UPDATE,
|
|
124
|
-
model=LoanAccount,
|
|
125
|
-
condition=HasChanged("status", has_changed=True) & IsEqual("status.name", value=Status.ACTIVE.value),
|
|
126
|
-
priority=Priority.HIGH,
|
|
127
|
-
)
|
|
128
|
-
@select_related("status") # This ensures status is preloaded
|
|
129
|
-
def _set_activated_date(self, old_records: list[LoanAccount], new_records: list[LoanAccount], **kwargs) -> None:
|
|
130
|
-
logger.info(f"Setting activated date for {new_records}")
|
|
131
|
-
# No queries in loops - status objects are preloaded
|
|
132
|
-
self._loan_account_service.set_activated_date(new_records)
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
## 🛡️ Safe Handling of Related Objects
|
|
136
|
-
|
|
137
|
-
Use the `safe_get_related_attr` utility function to safely access related object attributes:
|
|
138
|
-
|
|
139
|
-
```python
|
|
140
|
-
from django_bulk_hooks.conditions import safe_get_related_attr
|
|
141
|
-
|
|
142
|
-
# ✅ SAFE: Use safe_get_related_attr to handle None values
|
|
143
|
-
@hook(AFTER_CREATE, model=Transaction)
|
|
144
|
-
def process_transaction(self, new_records, old_records):
|
|
145
|
-
for transaction in new_records:
|
|
146
|
-
# Safely get the status name, returns None if status doesn't exist
|
|
147
|
-
status_name = safe_get_related_attr(transaction, 'status', 'name')
|
|
148
|
-
|
|
149
|
-
if status_name == "COMPLETE":
|
|
150
|
-
# Process the transaction
|
|
151
|
-
pass
|
|
152
|
-
elif status_name is None:
|
|
153
|
-
# Handle case where status is not set
|
|
154
|
-
print(f"Transaction {transaction.id} has no status")
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
### Complete Example
|
|
158
|
-
|
|
159
|
-
```python
|
|
160
|
-
from django.db import models
|
|
161
|
-
from django_bulk_hooks import hook, select_related
|
|
162
|
-
from django_bulk_hooks.conditions import safe_get_related_attr
|
|
163
|
-
|
|
164
|
-
class Status(models.Model):
|
|
165
|
-
name = models.CharField(max_length=50)
|
|
166
|
-
|
|
167
|
-
class Transaction(HookModelMixin, models.Model):
|
|
168
|
-
amount = models.DecimalField(max_digits=10, decimal_places=2)
|
|
169
|
-
status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)
|
|
170
|
-
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True)
|
|
171
|
-
|
|
172
|
-
class TransactionHandler:
|
|
173
|
-
@hook(Transaction, "before_create")
|
|
174
|
-
def set_default_status(self, new_records, old_records=None):
|
|
175
|
-
"""Set default status for new transactions."""
|
|
176
|
-
default_status = Status.objects.filter(name="PENDING").first()
|
|
177
|
-
for transaction in new_records:
|
|
178
|
-
if transaction.status is None:
|
|
179
|
-
transaction.status = default_status
|
|
180
|
-
|
|
181
|
-
@hook(Transaction, "after_create")
|
|
182
|
-
@select_related("status", "category") # Preload related objects
|
|
183
|
-
def process_transactions(self, new_records, old_records=None):
|
|
184
|
-
"""Process transactions based on their status."""
|
|
185
|
-
for transaction in new_records:
|
|
186
|
-
# ✅ SAFE: Get status name safely (no queries in loops)
|
|
187
|
-
status_name = safe_get_related_attr(transaction, 'status', 'name')
|
|
188
|
-
|
|
189
|
-
if status_name == "COMPLETE":
|
|
190
|
-
self._process_complete_transaction(transaction)
|
|
191
|
-
elif status_name == "FAILED":
|
|
192
|
-
self._process_failed_transaction(transaction)
|
|
193
|
-
elif status_name is None:
|
|
194
|
-
print(f"Transaction {transaction.id} has no status")
|
|
195
|
-
|
|
196
|
-
# ✅ SAFE: Check for related object existence (no queries in loops)
|
|
197
|
-
category = safe_get_related_attr(transaction, 'category')
|
|
198
|
-
if category:
|
|
199
|
-
print(f"Transaction {transaction.id} belongs to category: {category.name}")
|
|
200
|
-
|
|
201
|
-
def _process_complete_transaction(self, transaction):
|
|
202
|
-
# Process complete transaction logic
|
|
203
|
-
pass
|
|
204
|
-
|
|
205
|
-
def _process_failed_transaction(self, transaction):
|
|
206
|
-
# Process failed transaction logic
|
|
207
|
-
pass
|
|
208
|
-
```
|
|
209
|
-
|
|
210
|
-
### Best Practices for Related Objects
|
|
211
|
-
|
|
212
|
-
1. **Always use `@select_related`** when accessing related object attributes in hooks
|
|
213
|
-
2. **Use `safe_get_related_attr`** for safe access to related object attributes
|
|
214
|
-
3. **Set default values in `BEFORE_CREATE` hooks** to ensure related objects exist
|
|
215
|
-
4. **Handle None cases explicitly** to avoid unexpected behavior
|
|
216
|
-
5. **Use bulk operations efficiently** by fetching related objects once and reusing them
|
|
217
|
-
|
|
218
|
-
## 🔍 Performance Tips
|
|
219
|
-
|
|
220
|
-
### Monitor Query Count
|
|
221
|
-
|
|
222
|
-
```python
|
|
223
|
-
from django.db import connection, reset_queries
|
|
224
|
-
|
|
225
|
-
# Before your bulk operation
|
|
226
|
-
reset_queries()
|
|
227
|
-
|
|
228
|
-
# Your bulk operation
|
|
229
|
-
accounts = Account.objects.bulk_create(account_list)
|
|
230
|
-
|
|
231
|
-
# After your bulk operation
|
|
232
|
-
print(f"Total queries: {len(connection.queries)}")
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
### Use `@select_related` Strategically
|
|
236
|
-
|
|
237
|
-
```python
|
|
238
|
-
# Only select_related fields you actually use
|
|
239
|
-
@select_related("status") # Good - only what you need
|
|
240
|
-
@select_related("status", "category", "user", "account") # Only if you use all of them
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
### Avoid Nested Loops with Related Objects
|
|
244
|
-
|
|
245
|
-
```python
|
|
246
|
-
# ❌ Bad - nested loops with related objects
|
|
247
|
-
@hook(AFTER_CREATE, model=Order)
|
|
248
|
-
def process_orders(self, new_records, old_records):
|
|
249
|
-
for order in new_records:
|
|
250
|
-
for item in order.items.all(): # This causes queries!
|
|
251
|
-
process_item(item)
|
|
252
|
-
|
|
253
|
-
# ✅ Good - use prefetch_related for many-to-many/one-to-many
|
|
254
|
-
@hook(AFTER_CREATE, model=Order)
|
|
255
|
-
@select_related("customer")
|
|
256
|
-
def process_orders(self, new_records, old_records):
|
|
257
|
-
# Prefetch items for all orders at once
|
|
258
|
-
from django.db.models import Prefetch
|
|
259
|
-
orders_with_items = Order.objects.prefetch_related(
|
|
260
|
-
Prefetch('items', queryset=Item.objects.select_related('product'))
|
|
261
|
-
).filter(id__in=[order.id for order in new_records])
|
|
262
|
-
|
|
263
|
-
for order in orders_with_items:
|
|
264
|
-
for item in order.items.all(): # No queries here
|
|
265
|
-
process_item(item)
|
|
266
|
-
```
|
|
267
|
-
|
|
268
|
-
## 📚 API Reference
|
|
269
|
-
|
|
270
|
-
### Decorators
|
|
271
|
-
|
|
272
|
-
- `@hook(event, model, condition=None, priority=DEFAULT_PRIORITY)` - Register a hook
|
|
273
|
-
- `@select_related(*fields)` - Preload related fields to prevent queries in loops
|
|
274
|
-
|
|
275
|
-
### Conditions
|
|
276
|
-
|
|
277
|
-
- `IsEqual(field, value)` - Check if field equals value
|
|
278
|
-
- `HasChanged(field, has_changed=True)` - Check if field has changed
|
|
279
|
-
- `safe_get_related_attr(instance, field, attr=None)` - Safely get related object attributes
|
|
280
|
-
|
|
281
|
-
### Events
|
|
282
|
-
|
|
283
|
-
- `BEFORE_CREATE`, `AFTER_CREATE`
|
|
284
|
-
- `BEFORE_UPDATE`, `AFTER_UPDATE`
|
|
285
|
-
- `BEFORE_DELETE`, `AFTER_DELETE`
|
|
286
|
-
- `VALIDATE_CREATE`, `VALIDATE_UPDATE`, `VALIDATE_DELETE`
|
|
287
|
-
|
|
288
|
-
## 🤝 Contributing
|
|
289
|
-
|
|
290
|
-
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
291
|
-
|
|
292
|
-
## 📄 License
|
|
293
|
-
|
|
294
|
-
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
295
|
-
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
django_bulk_hooks/__init__.py,sha256=EAWve4HjrrIuPbl8uc1s1ISDM3RPDtwCvTOPRwFpX8w,1392
|
|
2
|
-
django_bulk_hooks/conditions.py,sha256=wDtY90Kv3xjWx8HEA4aAjva8fDDaYegJhn0Eu6G0F60,12150
|
|
3
|
-
django_bulk_hooks/constants.py,sha256=3x1H1fSUUNo0DZONN7GUVDuySZctTR-jtByBHmAIX5w,303
|
|
4
|
-
django_bulk_hooks/context.py,sha256=HVDT73uSzvgrOR6mdXTvsBm3hLOgBU8ant_mB7VlFuM,380
|
|
5
|
-
django_bulk_hooks/decorators.py,sha256=_bTcC4zJiRjpJIMBhjZbuTsqeR0y4GAQ70EJvp8Q0wU,2517
|
|
6
|
-
django_bulk_hooks/engine.py,sha256=T3vIrYDRfGLr6GQfDwwlQQKpEGzsCfCca012DfPl7Z4,6137
|
|
7
|
-
django_bulk_hooks/enums.py,sha256=Zo8_tJzuzZ2IKfVc7gZ-0tWPT8q1QhqZbAyoh9ZVJbs,381
|
|
8
|
-
django_bulk_hooks/handler.py,sha256=1viPTjT9U-5rUPETOtyGHp_UaSPNxVoSYhbBwIHigy8,6076
|
|
9
|
-
django_bulk_hooks/manager.py,sha256=DcVosEA4RS79KSYgw3Z14_a9Sd8CfxNNc5F3eSb8xc0,11459
|
|
10
|
-
django_bulk_hooks/models.py,sha256=U5nCxingZS2sznDjgW8fWo93SisA03WKcGpxxApqhuM,5519
|
|
11
|
-
django_bulk_hooks/queryset.py,sha256=7lLqhZ-XOYsZ1I3Loxi4Nhz79M8HlTYE413AW8nyeDI,1330
|
|
12
|
-
django_bulk_hooks/registry.py,sha256=MY-JOuDphsxay9GHqpZGY_NHGGkvqaH_8RW5kiStDuI,741
|
|
13
|
-
django_bulk_hooks-0.1.101.dist-info/LICENSE,sha256=dguKIcbDGeZD-vXWdLyErPUALYOvtX_fO4Zjhq481uk,1088
|
|
14
|
-
django_bulk_hooks-0.1.101.dist-info/METADATA,sha256=UgcHNzW2TURJUzwXHW4bcnDeaPUMh9ySdEl8FnIK8fY,10700
|
|
15
|
-
django_bulk_hooks-0.1.101.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
|
|
16
|
-
django_bulk_hooks-0.1.101.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|