django-bulk-hooks 0.1.110__tar.gz → 0.1.111__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.
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/PKG-INFO +1 -1
- django_bulk_hooks-0.1.111/django_bulk_hooks/manager.py +203 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/pyproject.toml +1 -1
- django_bulk_hooks-0.1.110/django_bulk_hooks/manager.py +0 -394
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/LICENSE +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/README.md +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/__init__.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/conditions.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/constants.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/context.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/decorators.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/engine.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/enums.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/handler.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/models.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/priority.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/queryset.py +0 -0
- {django_bulk_hooks-0.1.110 → django_bulk_hooks-0.1.111}/django_bulk_hooks/registry.py +0 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
from django.db import models, transaction
|
|
2
|
+
|
|
3
|
+
from django_bulk_hooks import engine
|
|
4
|
+
from django_bulk_hooks.constants import (
|
|
5
|
+
AFTER_CREATE,
|
|
6
|
+
AFTER_DELETE,
|
|
7
|
+
AFTER_UPDATE,
|
|
8
|
+
BEFORE_CREATE,
|
|
9
|
+
BEFORE_DELETE,
|
|
10
|
+
BEFORE_UPDATE,
|
|
11
|
+
VALIDATE_CREATE,
|
|
12
|
+
VALIDATE_DELETE,
|
|
13
|
+
VALIDATE_UPDATE,
|
|
14
|
+
)
|
|
15
|
+
from django_bulk_hooks.context import HookContext
|
|
16
|
+
from django_bulk_hooks.queryset import HookQuerySet
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BulkHookManager(models.Manager):
|
|
20
|
+
CHUNK_SIZE = 200
|
|
21
|
+
|
|
22
|
+
def get_queryset(self):
|
|
23
|
+
return HookQuerySet(self.model, using=self._db)
|
|
24
|
+
|
|
25
|
+
@transaction.atomic
|
|
26
|
+
def bulk_update(
|
|
27
|
+
self, objs, fields, bypass_hooks=False, bypass_validation=False, **kwargs
|
|
28
|
+
):
|
|
29
|
+
if not objs:
|
|
30
|
+
return []
|
|
31
|
+
|
|
32
|
+
model_cls = self.model
|
|
33
|
+
|
|
34
|
+
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
35
|
+
raise TypeError(
|
|
36
|
+
f"bulk_update expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
if not bypass_hooks:
|
|
40
|
+
# Load originals for hook comparison and ensure they match the order of new instances
|
|
41
|
+
original_map = {
|
|
42
|
+
obj.pk: obj for obj in model_cls.objects.filter(pk__in=[obj.pk for obj in objs])
|
|
43
|
+
}
|
|
44
|
+
originals = [original_map.get(obj.pk) for obj in objs]
|
|
45
|
+
|
|
46
|
+
ctx = HookContext(model_cls)
|
|
47
|
+
|
|
48
|
+
# Run validation hooks first
|
|
49
|
+
if not bypass_validation:
|
|
50
|
+
engine.run(model_cls, VALIDATE_UPDATE, objs, originals, ctx=ctx)
|
|
51
|
+
|
|
52
|
+
# Then run business logic hooks
|
|
53
|
+
engine.run(model_cls, BEFORE_UPDATE, objs, originals, ctx=ctx)
|
|
54
|
+
|
|
55
|
+
# Automatically detect fields that were modified during BEFORE_UPDATE hooks
|
|
56
|
+
modified_fields = self._detect_modified_fields(objs, originals)
|
|
57
|
+
if modified_fields:
|
|
58
|
+
# Convert to set for efficient union operation
|
|
59
|
+
fields_set = set(fields)
|
|
60
|
+
fields_set.update(modified_fields)
|
|
61
|
+
fields = list(fields_set)
|
|
62
|
+
|
|
63
|
+
for i in range(0, len(objs), self.CHUNK_SIZE):
|
|
64
|
+
chunk = objs[i : i + self.CHUNK_SIZE]
|
|
65
|
+
# Call the base implementation to avoid re-triggering this method
|
|
66
|
+
super(models.Manager, self).bulk_update(chunk, fields, **kwargs)
|
|
67
|
+
|
|
68
|
+
if not bypass_hooks:
|
|
69
|
+
engine.run(model_cls, AFTER_UPDATE, objs, originals, ctx=ctx)
|
|
70
|
+
|
|
71
|
+
return objs
|
|
72
|
+
|
|
73
|
+
def _detect_modified_fields(self, new_instances, original_instances):
|
|
74
|
+
"""
|
|
75
|
+
Detect fields that were modified during BEFORE_UPDATE hooks by comparing
|
|
76
|
+
new instances with their original values.
|
|
77
|
+
"""
|
|
78
|
+
if not original_instances:
|
|
79
|
+
return set()
|
|
80
|
+
|
|
81
|
+
modified_fields = set()
|
|
82
|
+
|
|
83
|
+
# Since original_instances is now ordered to match new_instances, we can zip them directly
|
|
84
|
+
for new_instance, original in zip(new_instances, original_instances):
|
|
85
|
+
if new_instance.pk is None or original is None:
|
|
86
|
+
continue
|
|
87
|
+
|
|
88
|
+
# Compare all fields to detect changes
|
|
89
|
+
for field in new_instance._meta.fields:
|
|
90
|
+
if field.name == "id":
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
new_value = getattr(new_instance, field.name)
|
|
94
|
+
original_value = getattr(original, field.name)
|
|
95
|
+
|
|
96
|
+
# Handle different field types appropriately
|
|
97
|
+
if field.is_relation:
|
|
98
|
+
# For foreign keys, compare the pk values
|
|
99
|
+
new_pk = new_value.pk if new_value else None
|
|
100
|
+
original_pk = original_value.pk if original_value else None
|
|
101
|
+
if new_pk != original_pk:
|
|
102
|
+
modified_fields.add(field.name)
|
|
103
|
+
else:
|
|
104
|
+
# For regular fields, use direct comparison
|
|
105
|
+
if new_value != original_value:
|
|
106
|
+
modified_fields.add(field.name)
|
|
107
|
+
|
|
108
|
+
return modified_fields
|
|
109
|
+
|
|
110
|
+
@transaction.atomic
|
|
111
|
+
def bulk_create(self, objs, bypass_hooks=False, bypass_validation=False, **kwargs):
|
|
112
|
+
model_cls = self.model
|
|
113
|
+
|
|
114
|
+
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
115
|
+
raise TypeError(
|
|
116
|
+
f"bulk_create expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
result = []
|
|
120
|
+
|
|
121
|
+
if not bypass_hooks:
|
|
122
|
+
ctx = HookContext(model_cls)
|
|
123
|
+
|
|
124
|
+
# Run validation hooks first
|
|
125
|
+
if not bypass_validation:
|
|
126
|
+
engine.run(model_cls, VALIDATE_CREATE, objs, ctx=ctx)
|
|
127
|
+
|
|
128
|
+
# Then run business logic hooks
|
|
129
|
+
engine.run(model_cls, BEFORE_CREATE, objs, ctx=ctx)
|
|
130
|
+
|
|
131
|
+
for i in range(0, len(objs), self.CHUNK_SIZE):
|
|
132
|
+
chunk = objs[i : i + self.CHUNK_SIZE]
|
|
133
|
+
result.extend(super(models.Manager, self).bulk_create(chunk, **kwargs))
|
|
134
|
+
|
|
135
|
+
if not bypass_hooks:
|
|
136
|
+
engine.run(model_cls, AFTER_CREATE, result, ctx=ctx)
|
|
137
|
+
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
@transaction.atomic
|
|
141
|
+
def bulk_delete(
|
|
142
|
+
self, objs, batch_size=None, bypass_hooks=False, bypass_validation=False
|
|
143
|
+
):
|
|
144
|
+
if not objs:
|
|
145
|
+
return []
|
|
146
|
+
|
|
147
|
+
model_cls = self.model
|
|
148
|
+
|
|
149
|
+
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
150
|
+
raise TypeError(
|
|
151
|
+
f"bulk_delete expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
ctx = HookContext(model_cls)
|
|
155
|
+
|
|
156
|
+
if not bypass_hooks:
|
|
157
|
+
# Run validation hooks first
|
|
158
|
+
if not bypass_validation:
|
|
159
|
+
engine.run(model_cls, VALIDATE_DELETE, objs, ctx=ctx)
|
|
160
|
+
|
|
161
|
+
# Then run business logic hooks
|
|
162
|
+
engine.run(model_cls, BEFORE_DELETE, objs, ctx=ctx)
|
|
163
|
+
|
|
164
|
+
pks = [obj.pk for obj in objs if obj.pk is not None]
|
|
165
|
+
|
|
166
|
+
# Use base manager for the actual deletion to prevent recursion
|
|
167
|
+
# The hooks have already been fired above, so we don't need them again
|
|
168
|
+
model_cls._base_manager.filter(pk__in=pks).delete()
|
|
169
|
+
|
|
170
|
+
if not bypass_hooks:
|
|
171
|
+
engine.run(model_cls, AFTER_DELETE, objs, ctx=ctx)
|
|
172
|
+
|
|
173
|
+
return objs
|
|
174
|
+
|
|
175
|
+
@transaction.atomic
|
|
176
|
+
def update(self, **kwargs):
|
|
177
|
+
objs = list(self.all())
|
|
178
|
+
if not objs:
|
|
179
|
+
return 0
|
|
180
|
+
for key, value in kwargs.items():
|
|
181
|
+
for obj in objs:
|
|
182
|
+
setattr(obj, key, value)
|
|
183
|
+
self.bulk_update(objs, fields=list(kwargs.keys()))
|
|
184
|
+
return len(objs)
|
|
185
|
+
|
|
186
|
+
@transaction.atomic
|
|
187
|
+
def delete(self):
|
|
188
|
+
objs = list(self.all())
|
|
189
|
+
if not objs:
|
|
190
|
+
return 0
|
|
191
|
+
self.bulk_delete(objs)
|
|
192
|
+
return len(objs)
|
|
193
|
+
|
|
194
|
+
@transaction.atomic
|
|
195
|
+
def save(self, obj):
|
|
196
|
+
if obj.pk:
|
|
197
|
+
self.bulk_update(
|
|
198
|
+
[obj],
|
|
199
|
+
fields=[field.name for field in obj._meta.fields if field.name != "id"],
|
|
200
|
+
)
|
|
201
|
+
else:
|
|
202
|
+
self.bulk_create([obj])
|
|
203
|
+
return obj
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "django-bulk-hooks"
|
|
3
|
-
version = "0.1.
|
|
3
|
+
version = "0.1.111"
|
|
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"
|
|
@@ -1,394 +0,0 @@
|
|
|
1
|
-
from django.db import models, transaction
|
|
2
|
-
|
|
3
|
-
from django_bulk_hooks import engine
|
|
4
|
-
from django_bulk_hooks.constants import (
|
|
5
|
-
AFTER_CREATE,
|
|
6
|
-
AFTER_DELETE,
|
|
7
|
-
AFTER_UPDATE,
|
|
8
|
-
BEFORE_CREATE,
|
|
9
|
-
BEFORE_DELETE,
|
|
10
|
-
BEFORE_UPDATE,
|
|
11
|
-
VALIDATE_CREATE,
|
|
12
|
-
VALIDATE_DELETE,
|
|
13
|
-
VALIDATE_UPDATE,
|
|
14
|
-
)
|
|
15
|
-
from django_bulk_hooks.context import HookContext
|
|
16
|
-
from django_bulk_hooks.queryset import HookQuerySet
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class BulkHookManager(models.Manager):
|
|
20
|
-
CHUNK_SIZE = 200
|
|
21
|
-
|
|
22
|
-
def get_queryset(self):
|
|
23
|
-
return HookQuerySet(self.model, using=self._db)
|
|
24
|
-
|
|
25
|
-
def _has_multi_table_inheritance(self, model_cls):
|
|
26
|
-
"""
|
|
27
|
-
Check if this model uses multi-table inheritance.
|
|
28
|
-
"""
|
|
29
|
-
if not model_cls._meta.parents:
|
|
30
|
-
return False
|
|
31
|
-
|
|
32
|
-
# Check if any parent is not abstract
|
|
33
|
-
for parent_model in model_cls._meta.parents.keys():
|
|
34
|
-
if not parent_model._meta.abstract:
|
|
35
|
-
return True
|
|
36
|
-
|
|
37
|
-
return False
|
|
38
|
-
|
|
39
|
-
def _get_base_model(self, model_cls):
|
|
40
|
-
"""
|
|
41
|
-
Get the base model (first non-abstract parent or self).
|
|
42
|
-
"""
|
|
43
|
-
base_model = model_cls
|
|
44
|
-
while base_model._meta.parents:
|
|
45
|
-
# Get the first non-abstract parent model
|
|
46
|
-
for parent_model in base_model._meta.parents.keys():
|
|
47
|
-
if not parent_model._meta.abstract:
|
|
48
|
-
base_model = parent_model
|
|
49
|
-
break
|
|
50
|
-
else:
|
|
51
|
-
# No non-abstract parents found, break the loop
|
|
52
|
-
break
|
|
53
|
-
return base_model
|
|
54
|
-
|
|
55
|
-
def _extract_base_objects(self, objs, model_cls):
|
|
56
|
-
"""
|
|
57
|
-
Extract base model objects from inherited objects.
|
|
58
|
-
"""
|
|
59
|
-
base_model = self._get_base_model(model_cls)
|
|
60
|
-
base_objects = []
|
|
61
|
-
|
|
62
|
-
for obj in objs:
|
|
63
|
-
base_obj = base_model()
|
|
64
|
-
for field in base_model._meta.fields:
|
|
65
|
-
# Skip ID field
|
|
66
|
-
if field.name == 'id':
|
|
67
|
-
continue
|
|
68
|
-
|
|
69
|
-
# Safely copy field values
|
|
70
|
-
try:
|
|
71
|
-
if hasattr(obj, field.name):
|
|
72
|
-
setattr(base_obj, field.name, getattr(obj, field.name))
|
|
73
|
-
except (AttributeError, ValueError):
|
|
74
|
-
# Skip fields that can't be copied
|
|
75
|
-
continue
|
|
76
|
-
|
|
77
|
-
base_objects.append(base_obj)
|
|
78
|
-
|
|
79
|
-
return base_objects
|
|
80
|
-
|
|
81
|
-
def _extract_child_objects(self, objs, model_cls):
|
|
82
|
-
"""
|
|
83
|
-
Extract child model objects from inherited objects.
|
|
84
|
-
"""
|
|
85
|
-
child_objects = []
|
|
86
|
-
|
|
87
|
-
for obj in objs:
|
|
88
|
-
child_obj = model_cls()
|
|
89
|
-
child_obj.pk = obj.pk # Set the same PK as base
|
|
90
|
-
|
|
91
|
-
# Copy only fields specific to this model
|
|
92
|
-
for field in model_cls._meta.fields:
|
|
93
|
-
# Skip ID field and fields that don't belong to this model
|
|
94
|
-
if field.name == 'id':
|
|
95
|
-
continue
|
|
96
|
-
|
|
97
|
-
# Check if this field belongs to the current model
|
|
98
|
-
# Use a safer way to check field ownership
|
|
99
|
-
try:
|
|
100
|
-
if hasattr(field, 'model') and field.model == model_cls:
|
|
101
|
-
# This field belongs to the current model
|
|
102
|
-
if hasattr(obj, field.name):
|
|
103
|
-
setattr(child_obj, field.name, getattr(obj, field.name))
|
|
104
|
-
except AttributeError:
|
|
105
|
-
# Skip fields that don't have proper model reference
|
|
106
|
-
continue
|
|
107
|
-
|
|
108
|
-
child_objects.append(child_obj)
|
|
109
|
-
|
|
110
|
-
return child_objects
|
|
111
|
-
|
|
112
|
-
def _bulk_create_inherited(self, objs, **kwargs):
|
|
113
|
-
"""
|
|
114
|
-
Handle bulk create for inherited models by handling each table separately.
|
|
115
|
-
"""
|
|
116
|
-
if not objs:
|
|
117
|
-
return []
|
|
118
|
-
|
|
119
|
-
model_cls = self.model
|
|
120
|
-
result = []
|
|
121
|
-
|
|
122
|
-
# Group objects by their actual class
|
|
123
|
-
objects_by_class = {}
|
|
124
|
-
for obj in objs:
|
|
125
|
-
obj_class = obj.__class__
|
|
126
|
-
if obj_class not in objects_by_class:
|
|
127
|
-
objects_by_class[obj_class] = []
|
|
128
|
-
objects_by_class[obj_class].append(obj)
|
|
129
|
-
|
|
130
|
-
for obj_class, class_objects in objects_by_class.items():
|
|
131
|
-
try:
|
|
132
|
-
# Check if this class has multi-table inheritance
|
|
133
|
-
parent_models = [p for p in obj_class._meta.get_parent_list()
|
|
134
|
-
if not p._meta.abstract]
|
|
135
|
-
|
|
136
|
-
if not parent_models:
|
|
137
|
-
# No inheritance, use standard bulk_create
|
|
138
|
-
chunk_result = super(models.Manager, self).bulk_create(class_objects, **kwargs)
|
|
139
|
-
result.extend(chunk_result)
|
|
140
|
-
continue
|
|
141
|
-
|
|
142
|
-
# Handle multi-table inheritance
|
|
143
|
-
# Step 1: Bulk create base objects with hooks
|
|
144
|
-
base_objects = self._extract_base_objects(class_objects, obj_class)
|
|
145
|
-
|
|
146
|
-
# Use the model's manager with hooks
|
|
147
|
-
base_model = self._get_base_model(obj_class)
|
|
148
|
-
|
|
149
|
-
# Try to avoid recursion by using raw SQL or _base_manager
|
|
150
|
-
try:
|
|
151
|
-
if hasattr(base_model.objects, 'bulk_create'):
|
|
152
|
-
# Use the base model's manager with hooks
|
|
153
|
-
created_base = base_model.objects.bulk_create(base_objects, **kwargs)
|
|
154
|
-
else:
|
|
155
|
-
# Fallback to _base_manager
|
|
156
|
-
created_base = base_model._base_manager.bulk_create(base_objects, **kwargs)
|
|
157
|
-
except RecursionError:
|
|
158
|
-
# If recursion error, use _base_manager directly
|
|
159
|
-
created_base = base_model._base_manager.bulk_create(base_objects, **kwargs)
|
|
160
|
-
|
|
161
|
-
# Step 2: Update original objects with base IDs
|
|
162
|
-
for obj, base_obj in zip(class_objects, created_base):
|
|
163
|
-
obj.pk = base_obj.pk
|
|
164
|
-
obj._state.adding = False
|
|
165
|
-
|
|
166
|
-
# Step 3: Bulk create child objects with hooks
|
|
167
|
-
child_objects = self._extract_child_objects(class_objects, obj_class)
|
|
168
|
-
if child_objects:
|
|
169
|
-
# Use _base_manager to avoid recursion with custom managers
|
|
170
|
-
try:
|
|
171
|
-
obj_class._base_manager.bulk_create(child_objects, **kwargs)
|
|
172
|
-
except RecursionError:
|
|
173
|
-
# If recursion error, use individual saves
|
|
174
|
-
for obj in child_objects:
|
|
175
|
-
obj.save()
|
|
176
|
-
|
|
177
|
-
result.extend(class_objects)
|
|
178
|
-
|
|
179
|
-
except Exception as e:
|
|
180
|
-
# Add debugging information
|
|
181
|
-
import logging
|
|
182
|
-
logger = logging.getLogger(__name__)
|
|
183
|
-
logger.error(f"Error in _bulk_create_inherited for {obj_class}: {e}")
|
|
184
|
-
logger.error(f"Model fields: {[f.name for f in obj_class._meta.fields]}")
|
|
185
|
-
logger.error(f"Base model: {self._get_base_model(obj_class)}")
|
|
186
|
-
logger.error(f"Base model manager: {self._get_base_model(obj_class).objects}")
|
|
187
|
-
|
|
188
|
-
# If it's a recursion error, try a simpler approach
|
|
189
|
-
if isinstance(e, RecursionError):
|
|
190
|
-
logger.error("Recursion error detected, trying fallback approach")
|
|
191
|
-
try:
|
|
192
|
-
# Fallback: use individual saves
|
|
193
|
-
for obj in class_objects:
|
|
194
|
-
obj.save()
|
|
195
|
-
result.extend(class_objects)
|
|
196
|
-
continue
|
|
197
|
-
except Exception as fallback_error:
|
|
198
|
-
logger.error(f"Fallback approach also failed: {fallback_error}")
|
|
199
|
-
|
|
200
|
-
raise
|
|
201
|
-
|
|
202
|
-
return result
|
|
203
|
-
|
|
204
|
-
@transaction.atomic
|
|
205
|
-
def bulk_update(
|
|
206
|
-
self, objs, fields, bypass_hooks=False, bypass_validation=False, **kwargs
|
|
207
|
-
):
|
|
208
|
-
if not objs:
|
|
209
|
-
return []
|
|
210
|
-
|
|
211
|
-
model_cls = self.model
|
|
212
|
-
|
|
213
|
-
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
214
|
-
raise TypeError(
|
|
215
|
-
f"bulk_update expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
216
|
-
)
|
|
217
|
-
|
|
218
|
-
if not bypass_hooks:
|
|
219
|
-
# Load originals for hook comparison and ensure they match the order of new instances
|
|
220
|
-
original_map = {
|
|
221
|
-
obj.pk: obj for obj in model_cls.objects.filter(pk__in=[obj.pk for obj in objs])
|
|
222
|
-
}
|
|
223
|
-
originals = [original_map.get(obj.pk) for obj in objs]
|
|
224
|
-
|
|
225
|
-
ctx = HookContext(model_cls)
|
|
226
|
-
|
|
227
|
-
# Run validation hooks first
|
|
228
|
-
if not bypass_validation:
|
|
229
|
-
engine.run(model_cls, VALIDATE_UPDATE, objs, originals, ctx=ctx)
|
|
230
|
-
|
|
231
|
-
# Then run business logic hooks
|
|
232
|
-
engine.run(model_cls, BEFORE_UPDATE, objs, originals, ctx=ctx)
|
|
233
|
-
|
|
234
|
-
# Automatically detect fields that were modified during BEFORE_UPDATE hooks
|
|
235
|
-
modified_fields = self._detect_modified_fields(objs, originals)
|
|
236
|
-
if modified_fields:
|
|
237
|
-
# Convert to set for efficient union operation
|
|
238
|
-
fields_set = set(fields)
|
|
239
|
-
fields_set.update(modified_fields)
|
|
240
|
-
fields = list(fields_set)
|
|
241
|
-
|
|
242
|
-
for i in range(0, len(objs), self.CHUNK_SIZE):
|
|
243
|
-
chunk = objs[i : i + self.CHUNK_SIZE]
|
|
244
|
-
# Call the base implementation to avoid re-triggering this method
|
|
245
|
-
super(models.Manager, self).bulk_update(chunk, fields, **kwargs)
|
|
246
|
-
|
|
247
|
-
if not bypass_hooks:
|
|
248
|
-
engine.run(model_cls, AFTER_UPDATE, objs, originals, ctx=ctx)
|
|
249
|
-
|
|
250
|
-
return objs
|
|
251
|
-
|
|
252
|
-
def _detect_modified_fields(self, new_instances, original_instances):
|
|
253
|
-
"""
|
|
254
|
-
Detect fields that were modified during BEFORE_UPDATE hooks by comparing
|
|
255
|
-
new instances with their original values.
|
|
256
|
-
"""
|
|
257
|
-
if not original_instances:
|
|
258
|
-
return set()
|
|
259
|
-
|
|
260
|
-
modified_fields = set()
|
|
261
|
-
|
|
262
|
-
# Since original_instances is now ordered to match new_instances, we can zip them directly
|
|
263
|
-
for new_instance, original in zip(new_instances, original_instances):
|
|
264
|
-
if new_instance.pk is None or original is None:
|
|
265
|
-
continue
|
|
266
|
-
|
|
267
|
-
# Compare all fields to detect changes
|
|
268
|
-
for field in new_instance._meta.fields:
|
|
269
|
-
if field.name == "id":
|
|
270
|
-
continue
|
|
271
|
-
|
|
272
|
-
new_value = getattr(new_instance, field.name)
|
|
273
|
-
original_value = getattr(original, field.name)
|
|
274
|
-
|
|
275
|
-
# Handle different field types appropriately
|
|
276
|
-
if field.is_relation:
|
|
277
|
-
# For foreign keys, compare the pk values
|
|
278
|
-
new_pk = new_value.pk if new_value else None
|
|
279
|
-
original_pk = original_value.pk if original_value else None
|
|
280
|
-
if new_pk != original_pk:
|
|
281
|
-
modified_fields.add(field.name)
|
|
282
|
-
else:
|
|
283
|
-
# For regular fields, use direct comparison
|
|
284
|
-
if new_value != original_value:
|
|
285
|
-
modified_fields.add(field.name)
|
|
286
|
-
|
|
287
|
-
return modified_fields
|
|
288
|
-
|
|
289
|
-
@transaction.atomic
|
|
290
|
-
def bulk_create(self, objs, bypass_hooks=False, bypass_validation=False, **kwargs):
|
|
291
|
-
model_cls = self.model
|
|
292
|
-
|
|
293
|
-
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
294
|
-
raise TypeError(
|
|
295
|
-
f"bulk_create expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
296
|
-
)
|
|
297
|
-
|
|
298
|
-
# Check if this model uses multi-table inheritance
|
|
299
|
-
has_multi_table_inheritance = self._has_multi_table_inheritance(model_cls)
|
|
300
|
-
|
|
301
|
-
result = []
|
|
302
|
-
|
|
303
|
-
if not bypass_hooks:
|
|
304
|
-
ctx = HookContext(model_cls)
|
|
305
|
-
|
|
306
|
-
# Run validation hooks first
|
|
307
|
-
if not bypass_validation:
|
|
308
|
-
engine.run(model_cls, VALIDATE_CREATE, objs, ctx=ctx)
|
|
309
|
-
|
|
310
|
-
# Then run business logic hooks
|
|
311
|
-
engine.run(model_cls, BEFORE_CREATE, objs, ctx=ctx)
|
|
312
|
-
|
|
313
|
-
# Perform bulk create in chunks
|
|
314
|
-
for i in range(0, len(objs), self.CHUNK_SIZE):
|
|
315
|
-
chunk = objs[i : i + self.CHUNK_SIZE]
|
|
316
|
-
|
|
317
|
-
if has_multi_table_inheritance:
|
|
318
|
-
# Use our multi-table bulk create
|
|
319
|
-
created_chunk = self._bulk_create_inherited(chunk, **kwargs)
|
|
320
|
-
else:
|
|
321
|
-
# Use Django's standard bulk create
|
|
322
|
-
created_chunk = super(models.Manager, self).bulk_create(chunk, **kwargs)
|
|
323
|
-
|
|
324
|
-
result.extend(created_chunk)
|
|
325
|
-
|
|
326
|
-
if not bypass_hooks:
|
|
327
|
-
engine.run(model_cls, AFTER_CREATE, result, ctx=ctx)
|
|
328
|
-
|
|
329
|
-
return result
|
|
330
|
-
|
|
331
|
-
@transaction.atomic
|
|
332
|
-
def bulk_delete(
|
|
333
|
-
self, objs, batch_size=None, bypass_hooks=False, bypass_validation=False
|
|
334
|
-
):
|
|
335
|
-
if not objs:
|
|
336
|
-
return []
|
|
337
|
-
|
|
338
|
-
model_cls = self.model
|
|
339
|
-
|
|
340
|
-
if any(not isinstance(obj, model_cls) for obj in objs):
|
|
341
|
-
raise TypeError(
|
|
342
|
-
f"bulk_delete expected instances of {model_cls.__name__}, but got {set(type(obj).__name__ for obj in objs)}"
|
|
343
|
-
)
|
|
344
|
-
|
|
345
|
-
ctx = HookContext(model_cls)
|
|
346
|
-
|
|
347
|
-
if not bypass_hooks:
|
|
348
|
-
# Run validation hooks first
|
|
349
|
-
if not bypass_validation:
|
|
350
|
-
engine.run(model_cls, VALIDATE_DELETE, objs, ctx=ctx)
|
|
351
|
-
|
|
352
|
-
# Then run business logic hooks
|
|
353
|
-
engine.run(model_cls, BEFORE_DELETE, objs, ctx=ctx)
|
|
354
|
-
|
|
355
|
-
pks = [obj.pk for obj in objs if obj.pk is not None]
|
|
356
|
-
|
|
357
|
-
# Use base manager for the actual deletion to prevent recursion
|
|
358
|
-
# The hooks have already been fired above, so we don't need them again
|
|
359
|
-
model_cls._base_manager.filter(pk__in=pks).delete()
|
|
360
|
-
|
|
361
|
-
if not bypass_hooks:
|
|
362
|
-
engine.run(model_cls, AFTER_DELETE, objs, ctx=ctx)
|
|
363
|
-
|
|
364
|
-
return objs
|
|
365
|
-
|
|
366
|
-
@transaction.atomic
|
|
367
|
-
def update(self, **kwargs):
|
|
368
|
-
objs = list(self.all())
|
|
369
|
-
if not objs:
|
|
370
|
-
return 0
|
|
371
|
-
for key, value in kwargs.items():
|
|
372
|
-
for obj in objs:
|
|
373
|
-
setattr(obj, key, value)
|
|
374
|
-
self.bulk_update(objs, fields=list(kwargs.keys()))
|
|
375
|
-
return len(objs)
|
|
376
|
-
|
|
377
|
-
@transaction.atomic
|
|
378
|
-
def delete(self):
|
|
379
|
-
objs = list(self.all())
|
|
380
|
-
if not objs:
|
|
381
|
-
return 0
|
|
382
|
-
self.bulk_delete(objs)
|
|
383
|
-
return len(objs)
|
|
384
|
-
|
|
385
|
-
@transaction.atomic
|
|
386
|
-
def save(self, obj):
|
|
387
|
-
if obj.pk:
|
|
388
|
-
self.bulk_update(
|
|
389
|
-
[obj],
|
|
390
|
-
fields=[field.name for field in obj._meta.fields if field.name != "id"],
|
|
391
|
-
)
|
|
392
|
-
else:
|
|
393
|
-
self.bulk_create([obj])
|
|
394
|
-
return obj
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|