django-bulk-hooks 0.1.81__tar.gz → 0.1.82__tar.gz

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.

Potentially problematic release.


This version of django-bulk-hooks might be problematic. Click here for more details.

@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: django-bulk-hooks
3
- Version: 0.1.81
3
+ Version: 0.1.82
4
4
  Summary: Hook-style hooks for Django bulk operations like bulk_create and bulk_update.
5
5
  License: MIT
6
6
  Keywords: django,bulk,hooks
@@ -1,47 +1,50 @@
1
- from django_bulk_hooks.constants import (
2
- AFTER_CREATE,
3
- AFTER_DELETE,
4
- AFTER_UPDATE,
5
- BEFORE_CREATE,
6
- BEFORE_DELETE,
7
- BEFORE_UPDATE,
8
- VALIDATE_CREATE,
9
- VALIDATE_DELETE,
10
- VALIDATE_UPDATE,
11
- )
12
- from django_bulk_hooks.conditions import (
13
- ChangesTo,
14
- HasChanged,
15
- IsEqual,
16
- IsNotEqual,
17
- WasEqual,
18
- )
19
- from django_bulk_hooks.decorators import hook, select_related
20
- from django_bulk_hooks.engine import safe_get_related_object, safe_get_related_attr
21
- from django_bulk_hooks.handler import HookHandler
22
- from django_bulk_hooks.models import HookModelMixin
23
- from django_bulk_hooks.enums import Priority
24
-
25
- __all__ = [
26
- "HookHandler",
27
- "HookModelMixin",
28
- "BEFORE_CREATE",
29
- "AFTER_CREATE",
30
- "BEFORE_UPDATE",
31
- "AFTER_UPDATE",
32
- "BEFORE_DELETE",
33
- "AFTER_DELETE",
34
- "VALIDATE_CREATE",
35
- "VALIDATE_UPDATE",
36
- "VALIDATE_DELETE",
37
- "safe_get_related_object",
38
- "safe_get_related_attr",
39
- "Priority",
40
- "hook",
41
- "select_related",
42
- "ChangesTo",
43
- "HasChanged",
44
- "IsEqual",
45
- "IsNotEqual",
46
- "WasEqual",
47
- ]
1
+ from django_bulk_hooks.constants import (
2
+ AFTER_CREATE,
3
+ AFTER_DELETE,
4
+ AFTER_UPDATE,
5
+ BEFORE_CREATE,
6
+ BEFORE_DELETE,
7
+ BEFORE_UPDATE,
8
+ VALIDATE_CREATE,
9
+ VALIDATE_DELETE,
10
+ VALIDATE_UPDATE,
11
+ )
12
+ from django_bulk_hooks.conditions import (
13
+ ChangesTo,
14
+ HasChanged,
15
+ IsEqual,
16
+ IsNotEqual,
17
+ WasEqual,
18
+ safe_get_related_object,
19
+ safe_get_related_attr,
20
+ is_field_set,
21
+ )
22
+ from django_bulk_hooks.decorators import hook, select_related
23
+ from django_bulk_hooks.handler import HookHandler
24
+ from django_bulk_hooks.models import HookModelMixin
25
+ from django_bulk_hooks.enums import Priority
26
+
27
+ __all__ = [
28
+ "HookHandler",
29
+ "HookModelMixin",
30
+ "BEFORE_CREATE",
31
+ "AFTER_CREATE",
32
+ "BEFORE_UPDATE",
33
+ "AFTER_UPDATE",
34
+ "BEFORE_DELETE",
35
+ "AFTER_DELETE",
36
+ "VALIDATE_CREATE",
37
+ "VALIDATE_UPDATE",
38
+ "VALIDATE_DELETE",
39
+ "safe_get_related_object",
40
+ "safe_get_related_attr",
41
+ "is_field_set",
42
+ "Priority",
43
+ "hook",
44
+ "select_related",
45
+ "ChangesTo",
46
+ "HasChanged",
47
+ "IsEqual",
48
+ "IsNotEqual",
49
+ "WasEqual",
50
+ ]
@@ -1,308 +1,351 @@
1
- from django.db import models
2
-
3
-
4
- def safe_get_related_object(instance, field_name):
5
- """
6
- Safely get a related object without raising RelatedObjectDoesNotExist.
7
- Returns None if the foreign key field is None or the related object doesn't exist.
8
- """
9
- if not hasattr(instance, field_name):
10
- return None
11
-
12
- # Get the foreign key field
13
- try:
14
- field = instance._meta.get_field(field_name)
15
- if not field.is_relation or field.many_to_many or field.one_to_many:
16
- return getattr(instance, field_name, None)
17
- except models.FieldDoesNotExist:
18
- return getattr(instance, field_name, None)
19
-
20
- # Check if the foreign key field is None
21
- fk_field_name = f"{field_name}_id"
22
- if hasattr(instance, fk_field_name) and getattr(instance, fk_field_name) is None:
23
- return None
24
-
25
- # Try to get the related object, but catch RelatedObjectDoesNotExist
26
- try:
27
- return getattr(instance, field_name)
28
- except field.related_model.RelatedObjectDoesNotExist:
29
- return None
30
-
31
-
32
- def safe_get_related_attr(instance, field_name, attr_name=None):
33
- """
34
- Safely get a related object or its attribute without raising RelatedObjectDoesNotExist.
35
-
36
- This is particularly useful in hooks where objects might not have their related
37
- fields populated yet (e.g., during bulk_create operations).
38
-
39
- Args:
40
- instance: The model instance
41
- field_name: The foreign key field name
42
- attr_name: Optional attribute name to access on the related object
43
-
44
- Returns:
45
- The related object, the attribute value, or None if not available
46
-
47
- Example:
48
- # Instead of: loan_transaction.status.name (which might fail)
49
- # Use: safe_get_related_attr(loan_transaction, 'status', 'name')
50
-
51
- status_name = safe_get_related_attr(loan_transaction, 'status', 'name')
52
- if status_name in {Status.COMPLETE.value, Status.FAILED.value}:
53
- # Process the transaction
54
- pass
55
- """
56
- related_obj = safe_get_related_object(instance, field_name)
57
- if related_obj is None:
58
- return None
59
-
60
- if attr_name is None:
61
- return related_obj
62
-
63
- return getattr(related_obj, attr_name, None)
64
-
65
-
66
- def safe_get_related_attr_with_fallback(instance, field_name, attr_name=None, fallback_value=None):
67
- """
68
- Enhanced version of safe_get_related_attr that provides fallback handling.
69
-
70
- This function is especially useful for bulk operations where related objects
71
- might not be fully loaded or might not exist yet.
72
-
73
- Args:
74
- instance: The model instance
75
- field_name: The foreign key field name
76
- attr_name: Optional attribute name to access on the related object
77
- fallback_value: Value to return if the related object or attribute doesn't exist
78
-
79
- Returns:
80
- The related object, the attribute value, or fallback_value if not available
81
- """
82
- # First try the standard safe access
83
- result = safe_get_related_attr(instance, field_name, attr_name)
84
- if result is not None:
85
- return result
86
-
87
- # If that fails, try to get the foreign key ID and fetch the object directly
88
- fk_field_name = f"{field_name}_id"
89
- if hasattr(instance, fk_field_name):
90
- fk_id = getattr(instance, fk_field_name)
91
- if fk_id is not None:
92
- try:
93
- # Get the field to determine the related model
94
- field = instance._meta.get_field(field_name)
95
- if field.is_relation and not field.many_to_many and not field.one_to_many:
96
- # Try to fetch the related object directly
97
- related_obj = field.related_model.objects.get(pk=fk_id)
98
- if attr_name is None:
99
- return related_obj
100
- return getattr(related_obj, attr_name, fallback_value)
101
- except (field.related_model.DoesNotExist, AttributeError):
102
- pass
103
-
104
- return fallback_value
105
-
106
-
107
- def resolve_dotted_attr(instance, dotted_path):
108
- """
109
- Recursively resolve a dotted attribute path, e.g., "type.category".
110
- This function is designed to work with pre-loaded foreign keys to avoid queries.
111
- """
112
- if instance is None:
113
- return None
114
-
115
- current = instance
116
- for attr in dotted_path.split("."):
117
- if current is None:
118
- return None
119
-
120
- # Check if this is a foreign key that might trigger a query
121
- if hasattr(current, '_meta') and hasattr(current._meta, 'get_field'):
122
- try:
123
- field = current._meta.get_field(attr)
124
- if field.is_relation and not field.many_to_many and not field.one_to_many:
125
- # For foreign keys, use safe access to prevent RelatedObjectDoesNotExist
126
- current = safe_get_related_object(current, attr)
127
- else:
128
- current = getattr(current, attr, None)
129
- except Exception:
130
- # If field lookup fails, fall back to regular attribute access
131
- current = getattr(current, attr, None)
132
- else:
133
- # Not a model instance, use regular attribute access
134
- current = getattr(current, attr, None)
135
-
136
- return current
137
-
138
-
139
- class HookCondition:
140
- def check(self, instance, original_instance=None):
141
- raise NotImplementedError
142
-
143
- def __call__(self, instance, original_instance=None):
144
- return self.check(instance, original_instance)
145
-
146
- def __and__(self, other):
147
- return AndCondition(self, other)
148
-
149
- def __or__(self, other):
150
- return OrCondition(self, other)
151
-
152
- def __invert__(self):
153
- return NotCondition(self)
154
-
155
-
156
- class IsNotEqual(HookCondition):
157
- def __init__(self, field, value, only_on_change=False):
158
- self.field = field
159
- self.value = value
160
- self.only_on_change = only_on_change
161
-
162
- def check(self, instance, original_instance=None):
163
- current = resolve_dotted_attr(instance, self.field)
164
- if self.only_on_change:
165
- if original_instance is None:
166
- return False
167
- previous = resolve_dotted_attr(original_instance, self.field)
168
- return previous == self.value and current != self.value
169
- else:
170
- return current != self.value
171
-
172
-
173
- class IsEqual(HookCondition):
174
- def __init__(self, field, value, only_on_change=False):
175
- self.field = field
176
- self.value = value
177
- self.only_on_change = only_on_change
178
-
179
- def check(self, instance, original_instance=None):
180
- current = resolve_dotted_attr(instance, self.field)
181
- if self.only_on_change:
182
- if original_instance is None:
183
- return False
184
- previous = resolve_dotted_attr(original_instance, self.field)
185
- return previous != self.value and current == self.value
186
- else:
187
- return current == self.value
188
-
189
-
190
- class HasChanged(HookCondition):
191
- def __init__(self, field, has_changed=True):
192
- self.field = field
193
- self.has_changed = has_changed
194
-
195
- def check(self, instance, original_instance=None):
196
- if not original_instance:
197
- return False
198
- current = resolve_dotted_attr(instance, self.field)
199
- previous = resolve_dotted_attr(original_instance, self.field)
200
- return (current != previous) == self.has_changed
201
-
202
-
203
- class WasEqual(HookCondition):
204
- def __init__(self, field, value, only_on_change=False):
205
- """
206
- Check if a field's original value was `value`.
207
- If only_on_change is True, only return True when the field has changed away from that value.
208
- """
209
- self.field = field
210
- self.value = value
211
- self.only_on_change = only_on_change
212
-
213
- def check(self, instance, original_instance=None):
214
- if original_instance is None:
215
- return False
216
- previous = resolve_dotted_attr(original_instance, self.field)
217
- if self.only_on_change:
218
- current = resolve_dotted_attr(instance, self.field)
219
- return previous == self.value and current != self.value
220
- else:
221
- return previous == self.value
222
-
223
-
224
- class ChangesTo(HookCondition):
225
- def __init__(self, field, value):
226
- """
227
- Check if a field's value has changed to `value`.
228
- Only returns True when original value != value and current value == value.
229
- """
230
- self.field = field
231
- self.value = value
232
-
233
- def check(self, instance, original_instance=None):
234
- if original_instance is None:
235
- return False
236
- previous = resolve_dotted_attr(original_instance, self.field)
237
- current = resolve_dotted_attr(instance, self.field)
238
- return previous != self.value and current == self.value
239
-
240
-
241
- class IsGreaterThan(HookCondition):
242
- def __init__(self, field, value):
243
- self.field = field
244
- self.value = value
245
-
246
- def check(self, instance, original_instance=None):
247
- current = resolve_dotted_attr(instance, self.field)
248
- return current is not None and current > self.value
249
-
250
-
251
- class IsGreaterThanOrEqual(HookCondition):
252
- def __init__(self, field, value):
253
- self.field = field
254
- self.value = value
255
-
256
- def check(self, instance, original_instance=None):
257
- current = resolve_dotted_attr(instance, self.field)
258
- return current is not None and current >= self.value
259
-
260
-
261
- class IsLessThan(HookCondition):
262
- def __init__(self, field, value):
263
- self.field = field
264
- self.value = value
265
-
266
- def check(self, instance, original_instance=None):
267
- current = resolve_dotted_attr(instance, self.field)
268
- return current is not None and current < self.value
269
-
270
-
271
- class IsLessThanOrEqual(HookCondition):
272
- def __init__(self, field, value):
273
- self.field = field
274
- self.value = value
275
-
276
- def check(self, instance, original_instance=None):
277
- current = resolve_dotted_attr(instance, self.field)
278
- return current is not None and current <= self.value
279
-
280
-
281
- class AndCondition(HookCondition):
282
- def __init__(self, cond1, cond2):
283
- self.cond1 = cond1
284
- self.cond2 = cond2
285
-
286
- def check(self, instance, original_instance=None):
287
- return self.cond1.check(instance, original_instance) and self.cond2.check(
288
- instance, original_instance
289
- )
290
-
291
-
292
- class OrCondition(HookCondition):
293
- def __init__(self, cond1, cond2):
294
- self.cond1 = cond1
295
- self.cond2 = cond2
296
-
297
- def check(self, instance, original_instance=None):
298
- return self.cond1.check(instance, original_instance) or self.cond2.check(
299
- instance, original_instance
300
- )
301
-
302
-
303
- class NotCondition(HookCondition):
304
- def __init__(self, cond):
305
- self.cond = cond
306
-
307
- def check(self, instance, original_instance=None):
308
- return not self.cond.check(instance, original_instance)
1
+ from django.db import models
2
+
3
+
4
+ def safe_get_related_object(instance, field_name):
5
+ """
6
+ Safely get a related object without raising RelatedObjectDoesNotExist.
7
+ Returns None if the foreign key field is None or the related object doesn't exist.
8
+ """
9
+ if not hasattr(instance, field_name):
10
+ return None
11
+
12
+ # Get the foreign key field
13
+ try:
14
+ field = instance._meta.get_field(field_name)
15
+ if not field.is_relation or field.many_to_many or field.one_to_many:
16
+ return getattr(instance, field_name, None)
17
+ except models.FieldDoesNotExist:
18
+ return getattr(instance, field_name, None)
19
+
20
+ # Check if the foreign key field is None
21
+ fk_field_name = f"{field_name}_id"
22
+ if hasattr(instance, fk_field_name) and getattr(instance, fk_field_name) is None:
23
+ return None
24
+
25
+ # Try to get the related object, but catch RelatedObjectDoesNotExist
26
+ try:
27
+ return getattr(instance, field_name)
28
+ except field.related_model.RelatedObjectDoesNotExist:
29
+ return None
30
+
31
+
32
+ def is_field_set(instance, field_name):
33
+ """
34
+ Check if a foreign key field is set without raising RelatedObjectDoesNotExist.
35
+
36
+ Args:
37
+ instance: The model instance
38
+ field_name: The foreign key field name
39
+
40
+ Returns:
41
+ True if the field is set, False otherwise
42
+ """
43
+ # Check the foreign key ID field first
44
+ fk_field_name = f"{field_name}_id"
45
+ if hasattr(instance, fk_field_name):
46
+ fk_value = getattr(instance, fk_field_name, None)
47
+ return fk_value is not None
48
+
49
+ # Fallback to checking the field directly
50
+ try:
51
+ return getattr(instance, field_name) is not None
52
+ except Exception:
53
+ return False
54
+
55
+
56
+ def safe_get_related_attr(instance, field_name, attr_name=None):
57
+ """
58
+ Safely get a related object or its attribute without raising RelatedObjectDoesNotExist.
59
+
60
+ This is particularly useful in hooks where objects might not have their related
61
+ fields populated yet (e.g., during bulk_create operations or on unsaved objects).
62
+
63
+ Args:
64
+ instance: The model instance
65
+ field_name: The foreign key field name
66
+ attr_name: Optional attribute name to access on the related object
67
+
68
+ Returns:
69
+ The related object, the attribute value, or None if not available
70
+
71
+ Example:
72
+ # Instead of: loan_transaction.status.name (which might fail)
73
+ # Use: safe_get_related_attr(loan_transaction, 'status', 'name')
74
+
75
+ status_name = safe_get_related_attr(loan_transaction, 'status', 'name')
76
+ if status_name in {Status.COMPLETE.value, Status.FAILED.value}:
77
+ # Process the transaction
78
+ pass
79
+ """
80
+ # For unsaved objects, check the foreign key ID field first
81
+ if instance.pk is None:
82
+ fk_field_name = f"{field_name}_id"
83
+ if hasattr(instance, fk_field_name):
84
+ fk_value = getattr(instance, fk_field_name, None)
85
+ if fk_value is None:
86
+ return None
87
+ # If we have an ID but the object isn't loaded, try to load it
88
+ try:
89
+ field = instance._meta.get_field(field_name)
90
+ if hasattr(field, 'related_model'):
91
+ related_obj = field.related_model.objects.get(id=fk_value)
92
+ if attr_name is None:
93
+ return related_obj
94
+ return getattr(related_obj, attr_name, None)
95
+ except (field.related_model.DoesNotExist, AttributeError):
96
+ return None
97
+
98
+ # For saved objects or when the above doesn't work, use the original method
99
+ related_obj = safe_get_related_object(instance, field_name)
100
+ if related_obj is None:
101
+ return None
102
+
103
+ if attr_name is None:
104
+ return related_obj
105
+
106
+ return getattr(related_obj, attr_name, None)
107
+
108
+
109
+ def safe_get_related_attr_with_fallback(instance, field_name, attr_name=None, fallback_value=None):
110
+ """
111
+ Enhanced version of safe_get_related_attr that provides fallback handling.
112
+
113
+ This function is especially useful for bulk operations where related objects
114
+ might not be fully loaded or might not exist yet.
115
+
116
+ Args:
117
+ instance: The model instance
118
+ field_name: The foreign key field name
119
+ attr_name: Optional attribute name to access on the related object
120
+ fallback_value: Value to return if the related object or attribute doesn't exist
121
+
122
+ Returns:
123
+ The related object, the attribute value, or fallback_value if not available
124
+ """
125
+ # First try the standard safe access
126
+ result = safe_get_related_attr(instance, field_name, attr_name)
127
+ if result is not None:
128
+ return result
129
+
130
+ # If that fails, try to get the foreign key ID and fetch the object directly
131
+ fk_field_name = f"{field_name}_id"
132
+ if hasattr(instance, fk_field_name):
133
+ fk_id = getattr(instance, fk_field_name)
134
+ if fk_id is not None:
135
+ try:
136
+ # Get the field to determine the related model
137
+ field = instance._meta.get_field(field_name)
138
+ if field.is_relation and not field.many_to_many and not field.one_to_many:
139
+ # Try to fetch the related object directly
140
+ related_obj = field.related_model.objects.get(pk=fk_id)
141
+ if attr_name is None:
142
+ return related_obj
143
+ return getattr(related_obj, attr_name, fallback_value)
144
+ except (field.related_model.DoesNotExist, AttributeError):
145
+ pass
146
+
147
+ return fallback_value
148
+
149
+
150
+ def resolve_dotted_attr(instance, dotted_path):
151
+ """
152
+ Recursively resolve a dotted attribute path, e.g., "type.category".
153
+ This function is designed to work with pre-loaded foreign keys to avoid queries.
154
+ """
155
+ if instance is None:
156
+ return None
157
+
158
+ current = instance
159
+ for attr in dotted_path.split("."):
160
+ if current is None:
161
+ return None
162
+
163
+ # Check if this is a foreign key that might trigger a query
164
+ if hasattr(current, '_meta') and hasattr(current._meta, 'get_field'):
165
+ try:
166
+ field = current._meta.get_field(attr)
167
+ if field.is_relation and not field.many_to_many and not field.one_to_many:
168
+ # For foreign keys, use safe access to prevent RelatedObjectDoesNotExist
169
+ current = safe_get_related_object(current, attr)
170
+ else:
171
+ current = getattr(current, attr, None)
172
+ except Exception:
173
+ # If field lookup fails, fall back to regular attribute access
174
+ current = getattr(current, attr, None)
175
+ else:
176
+ # Not a model instance, use regular attribute access
177
+ current = getattr(current, attr, None)
178
+
179
+ return current
180
+
181
+
182
+ class HookCondition:
183
+ def check(self, instance, original_instance=None):
184
+ raise NotImplementedError
185
+
186
+ def __call__(self, instance, original_instance=None):
187
+ return self.check(instance, original_instance)
188
+
189
+ def __and__(self, other):
190
+ return AndCondition(self, other)
191
+
192
+ def __or__(self, other):
193
+ return OrCondition(self, other)
194
+
195
+ def __invert__(self):
196
+ return NotCondition(self)
197
+
198
+
199
+ class IsNotEqual(HookCondition):
200
+ def __init__(self, field, value, only_on_change=False):
201
+ self.field = field
202
+ self.value = value
203
+ self.only_on_change = only_on_change
204
+
205
+ def check(self, instance, original_instance=None):
206
+ current = resolve_dotted_attr(instance, self.field)
207
+ if self.only_on_change:
208
+ if original_instance is None:
209
+ return False
210
+ previous = resolve_dotted_attr(original_instance, self.field)
211
+ return previous == self.value and current != self.value
212
+ else:
213
+ return current != self.value
214
+
215
+
216
+ class IsEqual(HookCondition):
217
+ def __init__(self, field, value, only_on_change=False):
218
+ self.field = field
219
+ self.value = value
220
+ self.only_on_change = only_on_change
221
+
222
+ def check(self, instance, original_instance=None):
223
+ current = resolve_dotted_attr(instance, self.field)
224
+ if self.only_on_change:
225
+ if original_instance is None:
226
+ return False
227
+ previous = resolve_dotted_attr(original_instance, self.field)
228
+ return previous != self.value and current == self.value
229
+ else:
230
+ return current == self.value
231
+
232
+
233
+ class HasChanged(HookCondition):
234
+ def __init__(self, field, has_changed=True):
235
+ self.field = field
236
+ self.has_changed = has_changed
237
+
238
+ def check(self, instance, original_instance=None):
239
+ if not original_instance:
240
+ return False
241
+ current = resolve_dotted_attr(instance, self.field)
242
+ previous = resolve_dotted_attr(original_instance, self.field)
243
+ return (current != previous) == self.has_changed
244
+
245
+
246
+ class WasEqual(HookCondition):
247
+ def __init__(self, field, value, only_on_change=False):
248
+ """
249
+ Check if a field's original value was `value`.
250
+ If only_on_change is True, only return True when the field has changed away from that value.
251
+ """
252
+ self.field = field
253
+ self.value = value
254
+ self.only_on_change = only_on_change
255
+
256
+ def check(self, instance, original_instance=None):
257
+ if original_instance is None:
258
+ return False
259
+ previous = resolve_dotted_attr(original_instance, self.field)
260
+ if self.only_on_change:
261
+ current = resolve_dotted_attr(instance, self.field)
262
+ return previous == self.value and current != self.value
263
+ else:
264
+ return previous == self.value
265
+
266
+
267
+ class ChangesTo(HookCondition):
268
+ def __init__(self, field, value):
269
+ """
270
+ Check if a field's value has changed to `value`.
271
+ Only returns True when original value != value and current value == value.
272
+ """
273
+ self.field = field
274
+ self.value = value
275
+
276
+ def check(self, instance, original_instance=None):
277
+ if original_instance is None:
278
+ return False
279
+ previous = resolve_dotted_attr(original_instance, self.field)
280
+ current = resolve_dotted_attr(instance, self.field)
281
+ return previous != self.value and current == self.value
282
+
283
+
284
+ class IsGreaterThan(HookCondition):
285
+ def __init__(self, field, value):
286
+ self.field = field
287
+ self.value = value
288
+
289
+ def check(self, instance, original_instance=None):
290
+ current = resolve_dotted_attr(instance, self.field)
291
+ return current is not None and current > self.value
292
+
293
+
294
+ class IsGreaterThanOrEqual(HookCondition):
295
+ def __init__(self, field, value):
296
+ self.field = field
297
+ self.value = value
298
+
299
+ def check(self, instance, original_instance=None):
300
+ current = resolve_dotted_attr(instance, self.field)
301
+ return current is not None and current >= self.value
302
+
303
+
304
+ class IsLessThan(HookCondition):
305
+ def __init__(self, field, value):
306
+ self.field = field
307
+ self.value = value
308
+
309
+ def check(self, instance, original_instance=None):
310
+ current = resolve_dotted_attr(instance, self.field)
311
+ return current is not None and current < self.value
312
+
313
+
314
+ class IsLessThanOrEqual(HookCondition):
315
+ def __init__(self, field, value):
316
+ self.field = field
317
+ self.value = value
318
+
319
+ def check(self, instance, original_instance=None):
320
+ current = resolve_dotted_attr(instance, self.field)
321
+ return current is not None and current <= self.value
322
+
323
+
324
+ class AndCondition(HookCondition):
325
+ def __init__(self, cond1, cond2):
326
+ self.cond1 = cond1
327
+ self.cond2 = cond2
328
+
329
+ def check(self, instance, original_instance=None):
330
+ return self.cond1.check(instance, original_instance) and self.cond2.check(
331
+ instance, original_instance
332
+ )
333
+
334
+
335
+ class OrCondition(HookCondition):
336
+ def __init__(self, cond1, cond2):
337
+ self.cond1 = cond1
338
+ self.cond2 = cond2
339
+
340
+ def check(self, instance, original_instance=None):
341
+ return self.cond1.check(instance, original_instance) or self.cond2.check(
342
+ instance, original_instance
343
+ )
344
+
345
+
346
+ class NotCondition(HookCondition):
347
+ def __init__(self, cond):
348
+ self.cond = cond
349
+
350
+ def check(self, instance, original_instance=None):
351
+ return not self.cond.check(instance, original_instance)
@@ -1,44 +1,53 @@
1
- import logging
2
-
3
- from django.core.exceptions import ValidationError
4
- from django.db import models
5
- from django_bulk_hooks.registry import get_hooks
6
- from django_bulk_hooks.conditions import safe_get_related_object, safe_get_related_attr
7
-
8
- logger = logging.getLogger(__name__)
9
-
10
-
11
- def run(model_cls, event, new_instances, original_instances=None, ctx=None):
12
- hooks = get_hooks(model_cls, event)
13
-
14
- if not hooks:
15
- return
16
-
17
- # For BEFORE_* events, run model.clean() first for validation
18
- if event.startswith("before_"):
19
- for instance in new_instances:
20
- try:
21
- instance.clean()
22
- except ValidationError as e:
23
- logger.error("Validation failed for %s: %s", instance, e)
24
- raise
25
-
26
- for handler_cls, method_name, condition, priority in hooks:
27
- handler_instance = handler_cls()
28
- func = getattr(handler_instance, method_name)
29
-
30
- to_process_new = []
31
- to_process_old = []
32
-
33
- for new, original in zip(
34
- new_instances,
35
- original_instances or [None] * len(new_instances),
36
- strict=True,
37
- ):
38
- if not condition or condition.check(new, original):
39
- to_process_new.append(new)
40
- to_process_old.append(original)
41
-
42
- if to_process_new:
43
- # Call the function with keyword arguments
44
- func(new_records=to_process_new, old_records=to_process_old if any(to_process_old) else None)
1
+ import logging
2
+
3
+ from django.core.exceptions import ValidationError
4
+ from django.db import models
5
+ from django_bulk_hooks.registry import get_hooks
6
+ from django_bulk_hooks.conditions import safe_get_related_object, safe_get_related_attr
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def run(model_cls, event, new_instances, original_instances=None, ctx=None):
12
+ hooks = get_hooks(model_cls, event)
13
+
14
+ if not hooks:
15
+ return
16
+
17
+ # For BEFORE_* events, run model.clean() first for validation
18
+ if event.startswith("before_"):
19
+ for instance in new_instances:
20
+ try:
21
+ instance.clean()
22
+ except ValidationError as e:
23
+ logger.error("Validation failed for %s: %s", instance, e)
24
+ raise
25
+ except Exception as e:
26
+ # Handle RelatedObjectDoesNotExist and other exceptions that might occur
27
+ # when accessing foreign key fields on unsaved objects
28
+ if "RelatedObjectDoesNotExist" in str(type(e).__name__):
29
+ logger.debug("Skipping validation for unsaved object with unset foreign keys: %s", e)
30
+ continue
31
+ else:
32
+ logger.error("Unexpected error during validation for %s: %s", instance, e)
33
+ raise
34
+
35
+ for handler_cls, method_name, condition, priority in hooks:
36
+ handler_instance = handler_cls()
37
+ func = getattr(handler_instance, method_name)
38
+
39
+ to_process_new = []
40
+ to_process_old = []
41
+
42
+ for new, original in zip(
43
+ new_instances,
44
+ original_instances or [None] * len(new_instances),
45
+ strict=True,
46
+ ):
47
+ if not condition or condition.check(new, original):
48
+ to_process_new.append(new)
49
+ to_process_old.append(original)
50
+
51
+ if to_process_new:
52
+ # Call the function with keyword arguments
53
+ func(new_records=to_process_new, old_records=to_process_old if any(to_process_old) else None)
@@ -28,8 +28,15 @@ class HookModelMixin(models.Model):
28
28
  This ensures that when Django calls clean() (like in admin forms),
29
29
  it triggers the VALIDATE_* hooks for validation only.
30
30
  """
31
+ # Call Django's clean first
31
32
  super().clean()
32
33
 
34
+ # Skip hook validation during admin form validation
35
+ # This prevents RelatedObjectDoesNotExist errors when Django hasn't
36
+ # fully set up the object's relationships yet
37
+ if hasattr(self, '_state') and getattr(self._state, 'validating', False):
38
+ return
39
+
33
40
  # Determine if this is a create or update operation
34
41
  is_create = self.pk is None
35
42
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "django-bulk-hooks"
3
- version = "0.1.81"
3
+ version = "0.1.82"
4
4
  description = "Hook-style hooks for Django bulk operations like bulk_create and bulk_update."
5
5
  authors = ["Konrad Beck <konrad.beck@merchantcapital.co.za>"]
6
6
  readme = "README.md"