django-modelcluster 6.5__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.
modelcluster/fields.py ADDED
@@ -0,0 +1,584 @@
1
+ from __future__ import unicode_literals
2
+
3
+ from django import VERSION as DJANGO_VERSION
4
+ from django.core import checks
5
+ from django.db import IntegrityError, connections, router
6
+ from django.db.models import CASCADE
7
+ from django.db.models.fields.related import ForeignKey, ManyToManyField
8
+ from django.utils.functional import cached_property
9
+
10
+ from django.db.models.fields.related import (
11
+ ReverseManyToOneDescriptor,
12
+ ManyToManyDescriptor,
13
+ )
14
+
15
+
16
+ from modelcluster.utils import sort_by_fields
17
+
18
+ from modelcluster.queryset import FakeQuerySet
19
+
20
+
21
+ def create_deferring_foreign_related_manager(related, original_manager_cls):
22
+ """
23
+ Create a DeferringRelatedManager class that wraps an ordinary RelatedManager
24
+ with 'deferring' behaviour: any updates to the object set (via e.g. add() or clear())
25
+ are written to a holding area rather than committed to the database immediately.
26
+ Writing to the database is deferred until the model is saved.
27
+ """
28
+
29
+ relation_name = related.get_accessor_name()
30
+ rel_field = related.field
31
+ rel_model = related.related_model
32
+ superclass = rel_model._default_manager.__class__
33
+
34
+ class DeferringRelatedManager(superclass):
35
+ def __init__(self, instance):
36
+ super().__init__()
37
+ self.model = rel_model
38
+ self.instance = instance
39
+
40
+ @property
41
+ def is_deferring(self):
42
+ return relation_name in getattr(
43
+ self.instance, "_cluster_related_objects", {}
44
+ )
45
+
46
+ def _get_cluster_related_objects(self):
47
+ # Helper to retrieve the instance's _cluster_related_objects dict,
48
+ # creating it if it does not already exist
49
+ try:
50
+ return self.instance._cluster_related_objects
51
+ except AttributeError:
52
+ cluster_related_objects = {}
53
+ self.instance._cluster_related_objects = cluster_related_objects
54
+ return cluster_related_objects
55
+
56
+ def get_live_query_set(self):
57
+ # deprecated; renamed to get_live_queryset to match the move from
58
+ # get_query_set to get_queryset in Django 1.6
59
+ return self.get_live_queryset()
60
+
61
+ def get_live_queryset(self):
62
+ """
63
+ return the original manager's queryset, which reflects the live database
64
+ """
65
+ return original_manager_cls(self.instance).get_queryset()
66
+
67
+ def get_queryset(self):
68
+ """
69
+ return the current object set with any updates applied,
70
+ wrapped up in a FakeQuerySet if it doesn't match the database state
71
+ """
72
+ try:
73
+ results = self.instance._cluster_related_objects[relation_name]
74
+ except (AttributeError, KeyError):
75
+ if self.instance.pk is None:
76
+ # use an empty fake queryset if the instance is unsaved
77
+ results = []
78
+ else:
79
+ return self.get_live_queryset()
80
+
81
+ return FakeQuerySet(related.related_model, results)
82
+
83
+ def _apply_rel_filters(self, queryset):
84
+ # Implemented as empty for compatibility sake
85
+ # But there is probably a better implementation of this function
86
+ #
87
+ # NOTE: _apply_rel_filters() must return a copy of the queryset
88
+ # to work correctly with prefetch
89
+ return queryset._next_is_sticky().all()
90
+
91
+ def get_prefetch_querysets(self, instances, querysets=None):
92
+ if querysets and len(querysets) != 1:
93
+ raise ValueError(
94
+ "get_prefetch_querysets() must be passed exactly one queryset"
95
+ )
96
+ queryset = querysets[0] if querysets else None
97
+ if queryset is None:
98
+ db = self._db or router.db_for_read(self.model, instance=instances[0])
99
+ queryset = super().get_queryset().using(db)
100
+
101
+ rel_obj_attr = rel_field.get_local_related_value
102
+ instance_attr = rel_field.get_foreign_related_value
103
+ instances_dict = dict((instance_attr(inst), inst) for inst in instances)
104
+
105
+ query = {"%s__in" % rel_field.name: instances}
106
+ qs = queryset.filter(**query)
107
+ # Since we just bypassed this class' get_queryset(), we must manage
108
+ # the reverse relation manually.
109
+ for rel_obj in qs:
110
+ instance = instances_dict[rel_obj_attr(rel_obj)]
111
+ setattr(rel_obj, rel_field.name, instance)
112
+ cache_name = rel_field.related_query_name()
113
+ return qs, rel_obj_attr, instance_attr, False, cache_name, False
114
+
115
+ # Remove once we only support Django 5.0+
116
+ if not DJANGO_VERSION >= (5, 0):
117
+
118
+ def get_prefetch_queryset(self, instances, queryset=None):
119
+ if queryset is None:
120
+ return self.get_prefetch_querysets(instances)
121
+ return self.get_prefetch_querysets(instances, querysets=[queryset])
122
+
123
+ def get_object_list(self):
124
+ """
125
+ return the mutable list that forms the current in-memory state of
126
+ this relation. If there is no such list (i.e. the manager is returning
127
+ querysets from the live database instead), one is created, populating it
128
+ with the live database state
129
+ """
130
+ cluster_related_objects = self._get_cluster_related_objects()
131
+
132
+ try:
133
+ object_list = cluster_related_objects[relation_name]
134
+ except KeyError:
135
+ if self.instance.pk is None:
136
+ object_list = []
137
+ else:
138
+ object_list = list(self.get_live_queryset())
139
+ cluster_related_objects[relation_name] = object_list
140
+
141
+ return object_list
142
+
143
+ def add(self, *new_items):
144
+ """
145
+ Add the passed items to the stored object set, but do not commit them
146
+ to the database
147
+ """
148
+ items = self.get_object_list()
149
+
150
+ for target in new_items:
151
+ item_matched = False
152
+ for i, item in enumerate(items):
153
+ if item == target:
154
+ # Replace the matched item with the new one. This ensures that any
155
+ # modifications to that item's fields take effect within the recordset -
156
+ # i.e. we can perform a virtual UPDATE to an object in the list
157
+ # by calling add(updated_object). Which is semantically a bit dubious,
158
+ # but it does the job...
159
+ items[i] = target
160
+ item_matched = True
161
+ break
162
+ if not item_matched:
163
+ items.append(target)
164
+
165
+ # update the foreign key on the added item to point back to the parent instance
166
+ setattr(target, related.field.name, self.instance)
167
+
168
+ # Sort list
169
+ if rel_model._meta.ordering and len(items) > 1:
170
+ sort_by_fields(items, rel_model._meta.ordering)
171
+
172
+ def remove(self, *items_to_remove):
173
+ """
174
+ Remove the passed items from the stored object set, but do not commit the change
175
+ to the database
176
+ """
177
+ items = self.get_object_list()
178
+
179
+ # filter items list in place: see http://stackoverflow.com/a/1208792/1853523
180
+ items[:] = [item for item in items if item not in items_to_remove]
181
+
182
+ def create(self, **kwargs):
183
+ items = self.get_object_list()
184
+ new_item = related.related_model(**kwargs)
185
+ items.append(new_item)
186
+ return new_item
187
+
188
+ def clear(self):
189
+ """
190
+ Clear the stored object set, without affecting the database
191
+ """
192
+ self.set([])
193
+
194
+ def set(self, objs, bulk=True, clear=False):
195
+ # cast objs to a list so that:
196
+ # 1) we can call len() on it (which we can't do on, say, a queryset)
197
+ # 2) if we need to sort it, we can do so without mutating the original
198
+ objs = list(objs)
199
+
200
+ cluster_related_objects = self._get_cluster_related_objects()
201
+
202
+ for obj in objs:
203
+ # update the foreign key on the added item to point back to the parent instance
204
+ setattr(obj, related.field.name, self.instance)
205
+
206
+ # Clone and sort the 'objs' list, if necessary
207
+ if rel_model._meta.ordering and len(objs) > 1:
208
+ sort_by_fields(objs, rel_model._meta.ordering)
209
+
210
+ cluster_related_objects[relation_name] = objs
211
+
212
+ def commit(self):
213
+ """
214
+ Apply any changes made to the stored object set to the database.
215
+ Any objects removed from the initial set will be deleted entirely
216
+ from the database.
217
+ """
218
+ if self.instance.pk is None:
219
+ raise IntegrityError(
220
+ "Cannot commit relation %r on an unsaved model" % relation_name
221
+ )
222
+
223
+ try:
224
+ final_items = self.instance._cluster_related_objects[relation_name]
225
+ except (AttributeError, KeyError):
226
+ # _cluster_related_objects entry never created => no changes to make
227
+ return
228
+
229
+ original_manager = original_manager_cls(self.instance)
230
+
231
+ live_items = list(original_manager.get_queryset())
232
+ for item in live_items:
233
+ if item not in final_items:
234
+ item.delete()
235
+
236
+ for item in final_items:
237
+ # Django 1.9+ bulk updates items by default which assumes
238
+ # that they have already been saved to the database.
239
+ # Disable this behaviour.
240
+ # https://code.djangoproject.com/ticket/18556
241
+ # https://github.com/django/django/commit/adc0c4fbac98f9cb975e8fa8220323b2de638b46
242
+ original_manager.add(item, bulk=False)
243
+
244
+ # purge the _cluster_related_objects entry, so we switch back to live SQL
245
+ del self.instance._cluster_related_objects[relation_name]
246
+
247
+ return DeferringRelatedManager
248
+
249
+
250
+ class ChildObjectsDescriptor(ReverseManyToOneDescriptor):
251
+ def __get__(self, instance, instance_type=None):
252
+ if instance is None:
253
+ return self
254
+
255
+ return self.child_object_manager_cls(instance)
256
+
257
+ def __set__(self, instance, value):
258
+ manager = self.__get__(instance)
259
+ manager.set(value)
260
+
261
+ @cached_property
262
+ def child_object_manager_cls(self):
263
+ return create_deferring_foreign_related_manager(
264
+ self.rel, self.related_manager_cls
265
+ )
266
+
267
+
268
+ class ParentalKey(ForeignKey):
269
+ related_accessor_class = ChildObjectsDescriptor
270
+
271
+ def __init__(self, *args, **kwargs):
272
+ kwargs.setdefault("on_delete", CASCADE)
273
+ super().__init__(*args, **kwargs)
274
+
275
+ def check(self, **kwargs):
276
+ from modelcluster.models import ClusterableModel
277
+
278
+ errors = super().check(**kwargs)
279
+
280
+ # Check that the destination model is a subclass of ClusterableModel.
281
+ # If self.rel.to is a string at this point, it means that Django has been unable
282
+ # to resolve it as a model name; if so, skip this test so that Django's own
283
+ # system checks can report the appropriate error
284
+ if isinstance(self.remote_field.model, type) and not issubclass(
285
+ self.remote_field.model, ClusterableModel
286
+ ):
287
+ errors.append(
288
+ checks.Error(
289
+ "ParentalKey must point to a subclass of ClusterableModel.",
290
+ hint="Change {model_name} into a ClusterableModel or use a ForeignKey instead.".format(
291
+ model_name=self.remote_field.model._meta.app_label
292
+ + "."
293
+ + self.remote_field.model.__name__,
294
+ ),
295
+ obj=self,
296
+ id="modelcluster.E001",
297
+ )
298
+ )
299
+
300
+ # ParentalKeys must have an accessor name (#49)
301
+ if self.remote_field.get_accessor_name() == "+":
302
+ errors.append(
303
+ checks.Error(
304
+ "related_name='+' is not allowed on ParentalKey fields",
305
+ hint="Either change it to a valid name or remove it",
306
+ obj=self,
307
+ id="modelcluster.E002",
308
+ )
309
+ )
310
+
311
+ return errors
312
+
313
+
314
+ def create_deferring_forward_many_to_many_manager(rel, original_manager_cls):
315
+ rel_field = rel.field
316
+ relation_name = rel_field.name
317
+ query_field_name = rel_field.related_query_name()
318
+ source_field_name = rel_field.m2m_field_name()
319
+ rel_model = rel.model
320
+ superclass = rel_model._default_manager.__class__
321
+ rel_through = rel.through
322
+
323
+ class DeferringManyRelatedManager(superclass):
324
+ def __init__(self, instance=None):
325
+ super().__init__()
326
+ self.model = rel_model
327
+ self.through = rel_through
328
+ self.instance = instance
329
+
330
+ def get_original_manager(self):
331
+ return original_manager_cls(self.instance)
332
+
333
+ def get_live_queryset(self):
334
+ """
335
+ return the original manager's queryset, which reflects the live database
336
+ """
337
+ return self.get_original_manager().get_queryset()
338
+
339
+ def _get_cluster_related_objects(self):
340
+ # Helper to retrieve the instance's _cluster_related_objects dict,
341
+ # creating it if it does not already exist
342
+ try:
343
+ return self.instance._cluster_related_objects
344
+ except AttributeError:
345
+ cluster_related_objects = {}
346
+ self.instance._cluster_related_objects = cluster_related_objects
347
+ return cluster_related_objects
348
+
349
+ def get_queryset(self):
350
+ """
351
+ return the current object set with any updates applied,
352
+ wrapped up in a FakeQuerySet if it doesn't match the database state
353
+ """
354
+ try:
355
+ results = self.instance._cluster_related_objects[relation_name]
356
+ except (AttributeError, KeyError):
357
+ if self.instance.pk:
358
+ return self.get_live_queryset()
359
+ else:
360
+ # the standard M2M manager fails on unsaved instances,
361
+ # so bypass it and return an empty queryset
362
+ return rel_model.objects.none()
363
+
364
+ return FakeQuerySet(rel_model, results)
365
+
366
+ def get_prefetch_querysets(self, instances, querysets=None):
367
+ # Derived from Django's ManyRelatedManager.get_prefetch_queryset.
368
+ if querysets and len(querysets) != 1:
369
+ raise ValueError(
370
+ "get_prefetch_querysets() must be passed exactly one queryset"
371
+ )
372
+ queryset = querysets[0] if querysets else None
373
+ if queryset is None:
374
+ queryset = super().get_queryset()
375
+
376
+ queryset._add_hints(instance=instances[0])
377
+ queryset = queryset.using(queryset._db or self._db)
378
+
379
+ query = {"%s__in" % query_field_name: instances}
380
+ queryset = queryset._next_is_sticky().filter(**query)
381
+
382
+ fk = self.through._meta.get_field(source_field_name)
383
+ join_table = fk.model._meta.db_table
384
+
385
+ connection = connections[queryset.db]
386
+ qn = connection.ops.quote_name
387
+
388
+ queryset = queryset.extra(
389
+ select={
390
+ "_prefetch_related_val_%s" % f.attname: "%s.%s"
391
+ % (qn(join_table), qn(f.column))
392
+ for f in fk.local_related_fields
393
+ }
394
+ )
395
+
396
+ return (
397
+ queryset,
398
+ lambda result: tuple(
399
+ getattr(result, "_prefetch_related_val_%s" % f.attname)
400
+ for f in fk.local_related_fields
401
+ ),
402
+ lambda inst: tuple(
403
+ f.get_db_prep_value(getattr(inst, f.attname), connection)
404
+ for f in fk.foreign_related_fields
405
+ ),
406
+ False,
407
+ relation_name,
408
+ False,
409
+ )
410
+
411
+ # Remove once we only support Django 5.0+
412
+ if not DJANGO_VERSION >= (5, 0):
413
+
414
+ def get_prefetch_queryset(self, instances, queryset=None):
415
+ if queryset is None:
416
+ return self.get_prefetch_querysets(instances)
417
+ return self.get_prefetch_querysets(instances, querysets=[queryset])
418
+
419
+ def _apply_rel_filters(self, queryset):
420
+ # Required for get_prefetch_queryset.
421
+ # NOTE: _apply_rel_filters() must return a copy of the queryset
422
+ # to work correctly with prefetch
423
+ return queryset._next_is_sticky().all()
424
+
425
+ def get_object_list(self):
426
+ """
427
+ return the mutable list that forms the current in-memory state of
428
+ this relation. If there is no such list (i.e. the manager is returning
429
+ querysets from the live database instead), one is created, populating it
430
+ with the live database state
431
+ """
432
+ cluster_related_objects = self._get_cluster_related_objects()
433
+
434
+ try:
435
+ object_list = cluster_related_objects[relation_name]
436
+ except KeyError:
437
+ object_list = list(self.get_live_queryset())
438
+ cluster_related_objects[relation_name] = object_list
439
+
440
+ return object_list
441
+
442
+ def add(self, *new_items):
443
+ """
444
+ Add the passed items to the stored object set, but do not commit them
445
+ to the database
446
+ """
447
+ items = self.get_object_list()
448
+
449
+ for target in new_items:
450
+ if target.pk is None:
451
+ raise ValueError(
452
+ '"%r" needs to have a primary key value before '
453
+ "it can be added to a parental many-to-many relation." % target
454
+ )
455
+ item_matched = False
456
+ for i, item in enumerate(items):
457
+ if item == target:
458
+ # Replace the matched item with the new one. This ensures that any
459
+ # modifications to that item's fields take effect within the recordset -
460
+ # i.e. we can perform a virtual UPDATE to an object in the list
461
+ # by calling add(updated_object). Which is semantically a bit dubious,
462
+ # but it does the job...
463
+ items[i] = target
464
+ item_matched = True
465
+ break
466
+ if not item_matched:
467
+ items.append(target)
468
+
469
+ # Sort list
470
+ if rel_model._meta.ordering and len(items) > 1:
471
+ sort_by_fields(items, rel_model._meta.ordering)
472
+
473
+ def clear(self):
474
+ """
475
+ Clear the stored object set, without affecting the database
476
+ """
477
+ self.set([])
478
+
479
+ def set_base(
480
+ self, objs, bulk=True, clear=False, through_defaults=None, raw=False
481
+ ):
482
+ # cast objs to a list so that:
483
+ # 1) we can call len() on it (which we can't do on, say, a queryset)
484
+ # 2) if we need to sort it, we can do so without mutating the original
485
+ objs = list(objs)
486
+
487
+ if objs and not isinstance(objs[0], rel_model):
488
+ # assume objs is a list of pks (like when loading data from a
489
+ # fixture), and allow the orignal manager to handle things
490
+ original_manager = self.get_original_manager()
491
+ original_manager.set(objs)
492
+ return
493
+
494
+ cluster_related_objects = self._get_cluster_related_objects()
495
+
496
+ # Clone and sort the 'objs' list, if necessary
497
+ if rel_model._meta.ordering and len(objs) > 1:
498
+ sort_by_fields(objs, rel_model._meta.ordering)
499
+
500
+ cluster_related_objects[relation_name] = objs
501
+
502
+ def set(self, objs, *, clear=False, through_defaults=None):
503
+ self.set_base(objs, clear=clear, through_defaults=through_defaults)
504
+
505
+ def remove(self, *items_to_remove):
506
+ """
507
+ Remove the passed items from the stored object set, but do not commit the change
508
+ to the database
509
+ """
510
+ items = self.get_object_list()
511
+
512
+ # filter items list in place: see http://stackoverflow.com/a/1208792/1853523
513
+ items[:] = [item for item in items if item not in items_to_remove]
514
+
515
+ def commit(self):
516
+ """
517
+ Apply any changes made to the stored object set to the database.
518
+ """
519
+ if not self.instance.pk:
520
+ raise IntegrityError(
521
+ "Cannot commit relation %r on an unsaved model" % relation_name
522
+ )
523
+
524
+ try:
525
+ final_items = self.instance._cluster_related_objects[relation_name]
526
+ except (AttributeError, KeyError):
527
+ # _cluster_related_objects entry never created => no changes to make
528
+ return
529
+
530
+ original_manager = self.get_original_manager()
531
+ live_items = list(original_manager.get_queryset())
532
+
533
+ items_to_remove = [item for item in live_items if item not in final_items]
534
+ items_to_add = [item for item in final_items if item not in live_items]
535
+
536
+ if items_to_remove:
537
+ original_manager.remove(*items_to_remove)
538
+ if items_to_add:
539
+ original_manager.add(*items_to_add)
540
+
541
+ # purge the _cluster_related_objects entry, so we switch back to live SQL
542
+ del self.instance._cluster_related_objects[relation_name]
543
+
544
+ return DeferringManyRelatedManager
545
+
546
+
547
+ class ParentalManyToManyDescriptor(ManyToManyDescriptor):
548
+ def __get__(self, instance, instance_type=None):
549
+ if instance is None:
550
+ return self
551
+
552
+ return self.child_object_manager_cls(instance)
553
+
554
+ def __set__(self, instance, value):
555
+ manager = self.__get__(instance)
556
+ manager.set(value)
557
+
558
+ @cached_property
559
+ def child_object_manager_cls(self):
560
+ rel = self.rel
561
+
562
+ return create_deferring_forward_many_to_many_manager(
563
+ rel, self.related_manager_cls
564
+ )
565
+
566
+
567
+ class ParentalManyToManyField(ManyToManyField):
568
+ related_accessor_class = ParentalManyToManyDescriptor
569
+ _need_commit_after_assignment = True
570
+
571
+ def contribute_to_class(self, cls, name, **kwargs):
572
+ # ManyToManyField does not (as of Django 1.10) respect related_accessor_class,
573
+ # but hard-codes ManyToManyDescriptor instead:
574
+ # https://github.com/django/django/blob/6157cd6da1b27716e8f3d1ed692a6e33d970ae46/django/db/models/fields/related.py#L1538
575
+ # So, we'll let the original contribute_to_class do its thing, and then overwrite
576
+ # the accessor...
577
+ super().contribute_to_class(cls, name, **kwargs)
578
+ setattr(cls, self.name, self.related_accessor_class(self.remote_field))
579
+
580
+ def value_from_object(self, obj):
581
+ # In Django >=1.10, ManyToManyField.value_from_object special-cases objects with no PK,
582
+ # returning an empty list on the basis that unsaved objects can't have related objects.
583
+ # Remove that special case.
584
+ return getattr(obj, self.attname).all()