Debian Codegraph @

docs/utilities.rst

raw
1 =======================
2 Miscellaneous Utilities
3 =======================
4
5 .. _Choices:
6
7 ``Choices``
8 ===========
9
10 .. note::
11
12 Django 3.0 adds `enumeration types <https://docs.djangoproject.com/en/3.0/releases/3.0/#enumerations-for-model-field-choices>`__.
13 These provide most of the same features as ``Choices``.
14
15 ``Choices`` provides some conveniences for setting ``choices`` on a Django model field:
16
17 .. code-block:: python
18
19 from model_utils import Choices
20
21 class Article(models.Model):
22 STATUS = Choices('draft', 'published')
23 status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)
24
25 A ``Choices`` object is initialized with any number of choices. In the
26 simplest case, each choice is a string; that string will be used both
27 as the database representation of the choice, and the human-readable
28 representation. Note that you can access options as attributes on the
29 ``Choices`` object: ``STATUS.draft``.
30
31 But you may want your human-readable versions translated, in which
32 case you need to separate the human-readable version from the DB
33 representation. In this case you can provide choices as two-tuples:
34
35 .. code-block:: python
36
37 from model_utils import Choices
38
39 class Article(models.Model):
40 STATUS = Choices(('draft', _('draft')), ('published', _('published')))
41 status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)
42
43 But what if your database representation of choices is constrained in
44 a way that would hinder readability of your code? For instance, you
45 may need to use an ``IntegerField`` rather than a ``CharField``, or
46 you may want the database to order the values in your field in some
47 specific way. In this case, you can provide your choices as triples,
48 where the first element is the database representation, the second is
49 a valid Python identifier you will use in your code as a constant, and
50 the third is the human-readable version:
51
52 .. code-block:: python
53
54 from model_utils import Choices
55
56 class Article(models.Model):
57 STATUS = Choices((0, 'draft', _('draft')), (1, 'published', _('published')))
58 status = models.IntegerField(choices=STATUS, default=STATUS.draft)
59
60 You can index into a ``Choices`` instance to translate a database
61 representation to its display name:
62
63 .. code-block:: python
64
65 status_display = Article.STATUS[article.status]
66
67 Option groups can also be used with ``Choices``; in that case each
68 argument is a tuple consisting of the option group name and a list of
69 options, where each option in the list is either a string, a two-tuple,
70 or a triple as outlined above. For example:
71
72 .. code-block:: python
73
74 from model_utils import Choices
75
76 class Article(models.Model):
77 STATUS = Choices(('Visible', ['new', 'archived']), ('Invisible', ['draft', 'deleted']))
78
79 Choices can be concatenated with the ``+`` operator, both to other Choices
80 instances and other iterable objects that could be converted into Choices:
81
82 .. code-block:: python
83
84 from model_utils import Choices
85
86 GENERIC_CHOICES = Choices((0, 'draft', _('draft')), (1, 'published', _('published')))
87
88 class Article(models.Model):
89 STATUS = GENERIC_CHOICES + [(2, 'featured', _('featured'))]
90 status = models.IntegerField(choices=STATUS, default=STATUS.draft)
91
92 Should you wish to provide a subset of choices for a field, for
93 instance, you have a form class to set some model instance to a failed
94 state, and only wish to show the user the failed outcomes from which to
95 select, you can use the ``subset`` method:
96
97 .. code-block:: python
98
99 from model_utils import Choices
100
101 OUTCOMES = Choices(
102 (0, 'success', _('Successful')),
103 (1, 'user_cancelled', _('Cancelled by the user')),
104 (2, 'admin_cancelled', _('Cancelled by an admin')),
105 )
106 FAILED_OUTCOMES = OUTCOMES.subset('user_cancelled', 'admin_cancelled')
107
108 The ``choices`` attribute on the model field can then be set to
109 ``FAILED_OUTCOMES``, thus allowing the subset to be defined in close
110 proximity to the definition of all the choices, and reused elsewhere as
111 required.
112
113
114 Field Tracker
115 =============
116
117 A ``FieldTracker`` can be added to a model to track changes in model fields. A
118 ``FieldTracker`` allows querying for field changes since a model instance was
119 last saved. An example of applying ``FieldTracker`` to a model:
120
121 .. code-block:: python
122
123 from django.db import models
124 from model_utils import FieldTracker
125
126 class Post(models.Model):
127 title = models.CharField(max_length=100)
128 body = models.TextField()
129
130 tracker = FieldTracker()
131
132 .. note::
133
134 ``django-model-utils`` 1.3.0 introduced the ``ModelTracker`` object for
135 tracking changes to model field values. Unfortunately ``ModelTracker``
136 suffered from some serious flaws in its handling of ``ForeignKey`` fields,
137 potentially resulting in many extra database queries if a ``ForeignKey``
138 field was tracked. In order to avoid breaking API backwards-compatibility,
139 ``ModelTracker`` retains the previous behavior but is deprecated, and
140 ``FieldTracker`` has been introduced to provide better ``ForeignKey``
141 handling. All uses of ``ModelTracker`` should be replaced by
142 ``FieldTracker``.
143
144 Summary of differences between ``ModelTracker`` and ``FieldTracker``:
145
146 * The previous value returned for a tracked ``ForeignKey`` field will now
147 be the raw ID rather than the full object (avoiding extra database
148 queries). (GH-43)
149
150 * The ``changed()`` method no longer returns the empty dictionary for all
151 unsaved instances; rather, ``None`` is considered to be the initial value
152 of all fields if the model has never been saved, thus ``changed()`` on an
153 unsaved instance will return a dictionary containing all fields whose
154 current value is not ``None``.
155
156 * The ``has_changed()`` method no longer crashes after an object's first
157 save. (GH-53).
158
159
160 Accessing a field tracker
161 -------------------------
162
163 There are multiple methods available for checking for changes in model fields.
164
165
166 previous
167 ~~~~~~~~
168 Returns the value of the given field during the last save:
169
170 .. code-block:: pycon
171
172 >>> a = Post.objects.create(title='First Post')
173 >>> a.title = 'Welcome'
174 >>> a.tracker.previous('title')
175 u'First Post'
176
177 Returns ``None`` when the model instance isn't saved yet.
178
179 If a field is `deferred`_, calling ``previous()`` will load the previous value from the database.
180
181 .. _deferred: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#defer
182
183
184 has_changed
185 ~~~~~~~~~~~
186 Returns ``True`` if the given field has changed since the last save. The ``has_changed`` method expects a single field:
187
188 .. code-block:: pycon
189
190 >>> a = Post.objects.create(title='First Post')
191 >>> a.title = 'Welcome'
192 >>> a.tracker.has_changed('title')
193 True
194 >>> a.tracker.has_changed('body')
195 False
196
197 The ``has_changed`` method relies on ``previous`` to determine whether a
198 field's values has changed.
199
200 If a field is `deferred`_ and has been assigned locally, calling ``has_changed()``
201 will load the previous value from the database to perform the comparison.
202
203 changed
204 ~~~~~~~
205 Returns a dictionary of all fields that have been changed since the last save
206 and the values of the fields during the last save:
207
208 .. code-block:: pycon
209
210 >>> a = Post.objects.create(title='First Post')
211 >>> a.title = 'Welcome'
212 >>> a.body = 'First post!'
213 >>> a.tracker.changed()
214 {'title': 'First Post', 'body': ''}
215
216 The ``changed`` method relies on ``has_changed`` to determine which fields
217 have changed.
218
219
220 Tracking specific fields
221 ------------------------
222
223 A fields parameter can be given to ``FieldTracker`` to limit tracking to
224 specific fields:
225
226 .. code-block:: python
227
228 from django.db import models
229 from model_utils import FieldTracker
230
231 class Post(models.Model):
232 title = models.CharField(max_length=100)
233 body = models.TextField()
234
235 title_tracker = FieldTracker(fields=['title'])
236
237 An example using the model specified above:
238
239 .. code-block:: pycon
240
241 >>> a = Post.objects.create(title='First Post')
242 >>> a.body = 'First post!'
243 >>> a.title_tracker.changed()
244 {'title': None}
245
246
247 Tracking Foreign Key Fields
248 ---------------------------
249
250 It should be noted that a generic FieldTracker tracks Foreign Keys by db_column name, rather than model field name, and would be accessed as follows:
251
252 .. code-block:: python
253
254 from django.db import models
255 from model_utils import FieldTracker
256
257 class Parent(models.Model):
258 name = models.CharField(max_length=64)
259
260 class Child(models.Model):
261 name = models.CharField(max_length=64)
262 parent = models.ForeignKey(Parent)
263 tracker = FieldTracker()
264
265 .. code-block:: pycon
266
267 >>> p = Parent.objects.create(name='P')
268 >>> c = Child.objects.create(name='C', parent=p)
269 >>> c.tracker.has_changed('parent_id')
270
271
272 To find the db_column names of your model (using the above example):
273
274 .. code-block:: pycon
275
276 >>> for field in Child._meta.fields:
277 field.get_attname_column()
278 ('id', 'id')
279 ('name', 'name')
280 ('parent_id', 'parent_id')
281
282
283 The model field name *may* be used when tracking with a specific tracker:
284
285 .. code-block:: python
286
287 specific_tracker = FieldTracker(fields=['parent'])
288
289 But according to issue #195 this is not recommended for accessing Foreign Key Fields.
290
291
292 Checking changes using signals
293 ------------------------------
294
295 The field tracker methods may also be used in ``pre_save`` and ``post_save``
296 signal handlers to identify field changes on model save.
297
298 .. NOTE::
299
300 Due to the implementation of ``FieldTracker``, ``post_save`` signal
301 handlers relying on field tracker methods should only be registered after
302 model creation.
303
304 FieldTracker implementation details
305 -----------------------------------
306
307 .. code-block:: python
308
309 from django.db import models
310 from model_utils import FieldTracker, TimeStampedModel
311
312 class MyModel(TimeStampedModel):
313 name = models.CharField(max_length=64)
314 tracker = FieldTracker()
315
316 def save(self, *args, **kwargs):
317 """ Automatically add "modified" to update_fields."""
318 update_fields = kwargs.get('update_fields')
319 if update_fields is not None:
320 kwargs['update_fields'] = set(update_fields) | {'modified'}
321 super().save(*args, **kwargs)
322
323 # [...]
324
325 instance = MyModel.objects.first()
326 instance.name = 'new'
327 instance.save(update_fields={'name'})
328
329 This is how ``FieldTracker`` tracks field changes on ``instance.save`` call.
330
331 1. In ``class_prepared`` handler ``FieldTracker`` patches ``save_base``,
332 ``refresh_from_db`` and ``__init__`` methods to reset initial state for tracked fields.
333 2. In the patched ``__init__`` method ``FieldTracker`` saves initial values for tracked
334 fields.
335 3. ``MyModel.save`` changes ``update_fields`` in order to store auto updated
336 ``modified`` timestamp. Complete list of saved fields is now known.
337 4. ``Model.save`` does nothing interesting except calling ``save_base``.
338 5. Decorated ``save_base()`` method calls ``super().save_base`` and all fields
339 that have values different to initial are considered as changed.
340 6. ``Model.save_base`` sends ``pre_save`` signal, saves instance to database and
341 sends ``post_save`` signal. All ``pre_save/post_save`` receivers can query
342 ``instance.tracker`` for a set of changed fields etc.
343 7. After ``Model.save_base`` return ``FieldTracker`` resets initial state for
344 updated fields (if no ``update_fields`` passed - whole initial state is
345 reset).
346 8. ``instance.refresh_from_db()`` call causes initial state reset like for
347 ``save_base()``.
348
349 When FieldTracker resets fields state
350 -------------------------------------
351
352 By the definition:
353
354 .. NOTE::
355 * Field value *is changed* if it differs from current database value.
356 * Field value *was changed* if value has changed in database and field state didn't reset.
357
358 .. code-block:: python
359
360 instance = Tracked.objects.get(pk=1)
361 # name not changed
362 instance.name += '_changed'
363 # name is changed
364 instance.save()
365 # name is not changed again
366
367 Current implementation resets fields state after ``post_save`` signals emitting. This is convenient for "outer" code
368 like in example above, but does not help when model ``save`` method is overridden.
369
370 .. code-block:: python
371
372 class MyModel(models.Model)
373 name = models.CharField(max_length=64)
374 tracker = FieldTracker()
375
376 def save(self): # erroneous implementation
377 self.name = self.name.replace(' ', '_')
378 name_changed = self.tracker.has_changed('name')
379 super().save()
380 # changed state has been reset here, so we need to store previous state somewhere else
381 if name_changed:
382 do_something_about_it()
383
384 ``FieldTracker`` provides a context manager interface to postpone fields state reset in complicate situations.
385
386 * Fields state resets after exiting from outer-most context
387 * By default, all fields are reset, but field list can be provided
388 * Fields are counted separately depending on field list passed to context managers
389 * Tracker can be used as decorator
390 * Different instances have their own context state
391 * Different trackers in same instance have separate context state
392
393 .. code-block:: python
394
395 class MyModel(models.Model)
396 name = models.CharField(max_length=64)
397 tracker = FieldTracker()
398
399 def save(self): # correct implementation
400 self.name = self.name.replace(' ', '_')
401
402 with self.tracker:
403 super().save()
404 # changed state reset is postponed
405 if self.tracker.has_changed('name'):
406 do_something_about_it()
407
408 # Decorator example
409 @tracker
410 def save(self): ...
411
412 # Restrict a set of fields to reset here
413 @tracker(fields=('name'))
414 def save(self): ...
415
416 # Context manager with field list
417 def save(self):
418 with self.tracker('name'):
419 ...
420