Debian Codegraph @

sortedm2m/fields.py

raw symbols SCIP
1 from functools import partial
2
3 from django.db import models, router, transaction
4 from django.db.models import Max, Model, signals
5 from django.db.models.fields.related import ManyToManyField as _ManyToManyField
6 from django.db.models.fields.related import lazy_related_operation, resolve_relation
7 from django.db.models.fields.related_descriptors import ManyToManyDescriptor, create_forward_many_to_many_manager
8 from django.db.models.utils import make_model_tuple
9 from django.utils.encoding import force_str
10 from django.utils.functional import cached_property
11 from django.utils.translation import gettext_lazy as _
12
13 from .compat import get_rel
14 from .forms import SortedMultipleChoiceField
15
16 SORT_VALUE_FIELD_NAME = 'sort_value'
17
18
19 def create_sorted_many_related_manager(superclass, rel, *args, **kwargs):
20 RelatedManager = create_forward_many_to_many_manager(
21 superclass, rel, *args, **kwargs)
22
23 class SortedRelatedManager(RelatedManager):
24 def _apply_rel_ordering(self, queryset):
25 return queryset.extra(order_by=['%s.%s' % (
26 self.through._meta.db_table,
27 self.through._sort_field_name, # pylint: disable=protected-access
28 )])
29
30 def get_queryset(self):
31 # We use ``extra`` method here because we have no other access to
32 # the extra sorting field of the intermediary model. The fields
33 # are hidden for joins because we set ``auto_created`` on the
34 # intermediary's meta options.
35 try:
36 # pylint: disable=protected-access
37 return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
38 except (AttributeError, KeyError):
39 queryset = super().get_queryset()
40 return self._apply_rel_ordering(queryset)
41
42 def get_prefetch_queryset(self, instances, queryset=None):
43 # Apply the same ordering for prefetch ones
44 result = super().get_prefetch_queryset(instances, queryset)
45 return (self._apply_rel_ordering(result[0]),) + result[1:]
46
47 def set(self, objs, **kwargs): # pylint: disable=arguments-differ
48 # Choosing to clear first will ensure the order is maintained.
49 kwargs['clear'] = True
50 super().set(objs, **kwargs)
51 set.alters_data = True
52
53 # pylint: disable=arguments-differ
54 def _add_items(self, source_field_name, target_field_name, *objs, **kwargs):
55 # source_field_name: the PK fieldname in join table for the source object
56 # target_field_name: the PK fieldname in join table for the target object
57 # *objs - objects to add. Either object instances, or primary keys of object instances.
58 # **kwargs: in Django >= 2.2; contains `through_defaults` key.
59 through_defaults = kwargs.get('through_defaults') or {}
60
61 # If there aren't any objects, there is nothing to do.
62 if objs:
63 # Django uses a set here, we need to use a list to keep the
64 # correct ordering.
65 new_ids = []
66 for obj in objs:
67 if isinstance(obj, self.model):
68 if not router.allow_relation(obj, self.instance):
69 raise ValueError(
70 'Cannot add "%r": instance is on database "%s", value is on database "%s"' %
71 (obj, self.instance._state.db, obj._state.db) # pylint: disable=protected-access
72 )
73
74 fk_val = self.through._meta.get_field(target_field_name).get_foreign_related_value(obj)[0]
75
76 if fk_val is None:
77 raise ValueError(
78 'Cannot add "%r": the value for field "%s" is None' %
79 (obj, target_field_name)
80 )
81
82 new_ids.append(fk_val)
83 elif isinstance(obj, Model):
84 raise TypeError(
85 "'%s' instance expected, got %r" %
86 (self.model._meta.object_name, obj)
87 )
88 else:
89 new_ids.append(obj)
90
91 db = router.db_for_write(self.through, instance=self.instance)
92 manager = self.through._default_manager.using(db) # pylint: disable=protected-access
93 vals = (self.through._default_manager.using(db) # pylint: disable=protected-access
94 .values_list(target_field_name, flat=True)
95 .filter(**{
96 source_field_name: self.related_val[0],
97 '%s__in' % target_field_name: new_ids,
98 }))
99
100 # make set.difference_update() keeping ordering
101 new_ids_set = set(new_ids)
102 new_ids_set.difference_update(vals)
103
104 new_ids = list(filter(lambda _id: _id in new_ids_set, new_ids))
105
106 # Add the ones that aren't there already
107 with transaction.atomic(using=db, savepoint=False):
108 if self.reverse or source_field_name == self.source_field_name:
109 # Don't send the signal when we are inserting the
110 # duplicate data row for symmetrical reverse entries.
111 signals.m2m_changed.send(
112 sender=self.through, action='pre_add',
113 instance=self.instance, reverse=self.reverse,
114 model=self.model, pk_set=new_ids_set, using=db,
115 )
116
117 rel_source_fk = self.related_val[0]
118 rel_through = self.through
119 sort_field_name = rel_through._sort_field_name # pylint: disable=protected-access
120
121 # Use the max of all indices as start index...
122 # maybe an autoincrement field should do the job more efficiently ?
123 source_queryset = manager.filter(**{'%s_id' % source_field_name: rel_source_fk})
124 sort_value_max = source_queryset.aggregate(max=Max(sort_field_name))['max'] or 0
125
126 bulk_data = [
127 dict(through_defaults, **{
128 '%s_id' % source_field_name: rel_source_fk,
129 '%s_id' % target_field_name: obj_id,
130 sort_field_name: obj_idx,
131 })
132 for obj_idx, obj_id in enumerate(new_ids, sort_value_max + 1)
133 ]
134
135 manager.bulk_create([rel_through(**data) for data in bulk_data])
136
137 if self.reverse or source_field_name == self.source_field_name:
138 # Don't send the signal when we are inserting the
139 # duplicate data row for symmetrical reverse entries.
140 signals.m2m_changed.send(
141 sender=self.through, action='post_add',
142 instance=self.instance, reverse=self.reverse,
143 model=self.model, pk_set=new_ids_set, using=db,
144 )
145
146 return SortedRelatedManager
147
148
149 class SortedManyToManyDescriptor(ManyToManyDescriptor):
150 def __init__(self, field):
151 super().__init__(field.remote_field)
152
153 @cached_property
154 def related_manager_cls(self):
155 model = self.rel.model
156 return create_sorted_many_related_manager(
157 model._default_manager.__class__, # pylint: disable=protected-access
158 self.rel,
159 # This is the new `reverse` argument (which ironically should
160 # be False)
161 reverse=False,
162 )
163
164
165 class SortedManyToManyField(_ManyToManyField):
166 """
167 Providing a many to many relation that remembers the order of related
168 objects.
169
170 Accept a boolean ``sorted`` attribute which specifies if relation is
171 ordered or not. Default is set to ``True``. If ``sorted`` is set to
172 ``False`` the field will behave exactly like django's ``ManyToManyField``.
173
174 Accept a class ``base_class`` attribute which specifies the base class of
175 the intermediate model. It allows to customize the intermediate model.
176 """
177
178 def __init__(self, to, sorted=True, base_class=None, **kwargs): # pylint: disable=redefined-builtin
179 self.sorted = sorted
180 self.sort_value_field_name = kwargs.pop(
181 'sort_value_field_name',
182 SORT_VALUE_FIELD_NAME)
183
184 # Base class of through model
185 self.base_class = base_class
186
187 super().__init__(to, **kwargs)
188 if self.sorted:
189 self.help_text = kwargs.get('help_text', None)
190
191 def deconstruct(self):
192 # We have to persist custom added options in the ``kwargs``
193 # dictionary. For readability only non-default values are stored.
194 name, path, args, kwargs = super().deconstruct()
195 if self.sort_value_field_name is not SORT_VALUE_FIELD_NAME:
196 kwargs['sort_value_field_name'] = self.sort_value_field_name
197 if self.sorted is not True:
198 kwargs['sorted'] = self.sorted
199 return name, path, args, kwargs
200
201 def check(self, **kwargs):
202 return (
203 super().check(**kwargs) +
204 self._check_through_sortedm2m()
205 )
206
207 def _check_through_sortedm2m(self):
208 rel = get_rel(self)
209
210 # Check if the custom through model of a SortedManyToManyField as a
211 # valid '_sort_field_name' attribute
212 if self.sorted and rel.through:
213 assert hasattr(rel.through, '_sort_field_name'), (
214 "The model is used as an intermediate model by "
215 "'%s' but has no defined '_sort_field_name' attribute" % rel.through
216 )
217
218 return []
219
220 # pylint: disable=inconsistent-return-statements
221 def contribute_to_class(self, cls, name, **kwargs):
222 if not self.sorted:
223 return super().contribute_to_class(cls, name, **kwargs)
224
225 # To support multiple relations to self, it's useful to have a non-None
226 # related name on symmetrical relations for internal reasons. The
227 # concept doesn't make a lot of sense externally ("you want me to
228 # specify *what* on my non-reversible relation?!"), so we set it up
229 # automatically. The funky name reduces the chance of an accidental
230 # clash.
231 rel = get_rel(self)
232
233 if rel.symmetrical and (rel.model == "self" or rel.model == cls._meta.object_name):
234 rel.related_name = "%s_rel_+" % name
235 elif rel.is_hidden():
236 # If the backwards relation is disabled, replace the original
237 # related_name with one generated from the m2m field name. Django
238 # still uses backwards relations internally and we need to avoid
239 # clashes between multiple m2m fields with related_name == '+'.
240 rel.related_name = "_%s_%s_+" % (cls.__name__.lower(), name)
241
242 # pylint: disable=bad-super-call
243 super(_ManyToManyField, self).contribute_to_class(cls, name, **kwargs)
244
245 # The intermediate m2m model is not auto created if:
246 # 1) There is a manually specified intermediate, or
247 # 2) The class owning the m2m field is abstract.
248 # 3) The class owning the m2m field has been swapped out.
249 if not cls._meta.abstract:
250 if rel.through:
251 def resolve_through_model(_, model):
252 rel.through = model
253 lazy_related_operation(resolve_through_model, cls, rel.through)
254 elif not cls._meta.swapped:
255 rel.through = self.create_intermediate_model(cls)
256
257 # Add the descriptor for the m2m relation
258 setattr(cls, self.name, SortedManyToManyDescriptor(self))
259
260 # Set up the accessor for the m2m table name for the relation
261 self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) # pylint: disable=attribute-defined-outside-init
262
263 def get_internal_type(self):
264 return 'ManyToManyField'
265
266 def formfield(self, **kwargs): # pylint: disable=arguments-differ
267 defaults = {}
268 if self.sorted:
269 defaults['form_class'] = SortedMultipleChoiceField
270 defaults.update(kwargs)
271 return super().formfield(**defaults)
272
273 def create_intermediate_model(self, klass):
274 base_classes = (self.base_class, models.Model) if self.base_class else (models.Model,)
275
276 return create_sortable_many_to_many_intermediary_model(
277 self, klass, self.sort_value_field_name,
278 base_classes=base_classes)
279
280
281 def create_sortable_many_to_many_intermediary_model(field, klass, sort_field_name, base_classes=None):
282 def set_managed(model, related, through):
283 through._meta.managed = model._meta.managed or related._meta.managed
284
285 to_model = resolve_relation(klass, field.remote_field.model)
286 name = '%s_%s' % (klass._meta.object_name, field.name)
287 lazy_related_operation(set_managed, klass, to_model, name)
288 base_classes = base_classes if base_classes else (models.Model,)
289
290 # TODO : use autoincrement here ?
291 sort_field = models.IntegerField(default=0)
292
293 to = make_model_tuple(to_model)[1]
294 from_ = klass._meta.model_name
295 if to == from_:
296 to = 'to_%s' % to
297 from_ = 'from_%s' % from_
298
299 meta = type('Meta', (), {
300 'db_table': field._get_m2m_db_table(klass._meta), # pylint: disable=protected-access
301 'auto_created': klass,
302 'app_label': klass._meta.app_label,
303 'db_tablespace': klass._meta.db_tablespace,
304 'unique_together': (from_, to),
305 'ordering': (sort_field_name,),
306 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to},
307 'verbose_name_plural': _('%(from)s-%(to)s relationships') % {'from': from_, 'to': to},
308 'apps': field.model._meta.apps,
309 })
310
311 # Construct and return the new class.
312 return type(force_str(name), base_classes, {
313 'Meta': meta,
314 '__module__': klass.__module__,
315 from_: models.ForeignKey(
316 klass,
317 related_name='%s+' % name,
318 db_tablespace=field.db_tablespace,
319 db_constraint=field.remote_field.db_constraint,
320 on_delete=models.CASCADE,
321 ),
322 to: models.ForeignKey(
323 to_model,
324 related_name='%s+' % name,
325 db_tablespace=field.db_tablespace,
326 db_constraint=field.remote_field.db_constraint,
327 on_delete=models.CASCADE,
328 ),
329 # Sort fields
330 sort_field_name: sort_field,
331 '_sort_field_name': sort_field_name,
332 })