Debian Codegraph @

docs/releases/2.2.txt

raw
1 ========================
2 Django 2.2 release notes
3 ========================
4
5 *April 1, 2019*
6
7 Welcome to Django 2.2!
8
9 These release notes cover the :ref:`new features <whats-new-2.2>`, as well as
10 some :ref:`backwards incompatible changes <backwards-incompatible-2.2>` you'll
11 want to be aware of when upgrading from Django 2.1 or earlier. We've
12 :ref:`begun the deprecation process for some features
13 <deprecated-features-2.2>`.
14
15 See the :doc:`/howto/upgrade-version` guide if you're updating an existing
16 project.
17
18 Django 2.2 is designated as a :term:`long-term support release
19 <Long-term support release>`. It will receive security updates for at least
20 three years after its release. Support for the previous LTS, Django 1.11, will
21 end in April 2020.
22
23 Python compatibility
24 ====================
25
26 Django 2.2 supports Python 3.5, 3.6, 3.7, 3.8 (as of 2.2.8), and 3.9 (as of
27 2.2.17). We **highly recommend** and only officially support the latest release
28 of each series.
29
30 .. _whats-new-2.2:
31
32 What's new in Django 2.2
33 ========================
34
35 Constraints
36 -----------
37
38 The new :class:`~django.db.models.CheckConstraint` and
39 :class:`~django.db.models.UniqueConstraint` classes enable adding custom
40 database constraints. Constraints are added to models using the
41 :attr:`Meta.constraints <django.db.models.Options.constraints>` option.
42
43 Minor features
44 --------------
45
46 :mod:`django.contrib.admin`
47 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
48
49 * Added a CSS class to the column headers of
50 :class:`~django.contrib.admin.TabularInline`.
51
52 :mod:`django.contrib.auth`
53 ~~~~~~~~~~~~~~~~~~~~~~~~~~
54
55 * The ``HttpRequest`` is now passed as the first positional argument to
56 :meth:`.RemoteUserBackend.configure_user`, if it accepts it.
57
58 :mod:`django.contrib.gis`
59 ~~~~~~~~~~~~~~~~~~~~~~~~~
60
61 * Added Oracle support for the
62 :class:`~django.contrib.gis.db.models.functions.Envelope` function.
63
64 * Added SpatiaLite support for the :lookup:`coveredby` and :lookup:`covers`
65 lookups.
66
67 :mod:`django.contrib.postgres`
68 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69
70 * The new ``ordering`` argument for
71 :class:`~django.contrib.postgres.aggregates.ArrayAgg` and
72 :class:`~django.contrib.postgres.aggregates.StringAgg` determines the
73 ordering of the aggregated elements.
74
75 * The new :class:`~django.contrib.postgres.indexes.BTreeIndex`,
76 :class:`~django.contrib.postgres.indexes.HashIndex` and
77 :class:`~django.contrib.postgres.indexes.SpGistIndex` classes allow
78 creating ``B-Tree``, ``hash``, and ``SP-GiST`` indexes in the database.
79
80 * :class:`~django.contrib.postgres.indexes.BrinIndex` now has the
81 ``autosummarize`` parameter.
82
83 * The new ``search_type`` parameter of
84 :class:`~django.contrib.postgres.search.SearchQuery` allows searching for
85 a phrase or raw expression.
86
87 :mod:`django.contrib.staticfiles`
88 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89
90 * Added path matching to the :option:`collectstatic --ignore` option so that
91 patterns like ``/vendor/*.js`` can be used.
92
93 Database backends
94 ~~~~~~~~~~~~~~~~~
95
96 * Added result streaming for :meth:`.QuerySet.iterator` on SQLite.
97
98 Generic Views
99 ~~~~~~~~~~~~~
100
101 * The new :meth:`View.setup <django.views.generic.base.View.setup>` hook
102 initializes view attributes before calling
103 :meth:`~django.views.generic.base.View.dispatch`. It allows mixins to set up
104 instance attributes for reuse in child classes.
105
106 Internationalization
107 ~~~~~~~~~~~~~~~~~~~~
108
109 * Added support and translations for the Armenian language.
110
111 Management Commands
112 ~~~~~~~~~~~~~~~~~~~
113
114 * The new :option:`--force-color` option forces colorization of the command
115 output.
116
117 * :djadmin:`inspectdb` now creates models for foreign tables on PostgreSQL.
118
119 * :option:`inspectdb --include-views` now creates models for materialized views
120 on Oracle and PostgreSQL.
121
122 * The new :option:`inspectdb --include-partitions` option allows creating
123 models for partition tables on PostgreSQL. In older versions, models are
124 created child tables instead the parent.
125
126 * :djadmin:`inspectdb` now introspects :class:`~django.db.models.DurationField`
127 for Oracle and PostgreSQL, and :class:`~django.db.models.AutoField` for
128 SQLite.
129
130 * On Oracle, :djadmin:`dbshell` is wrapped with ``rlwrap``, if available.
131 ``rlwrap`` provides a command history and editing of keyboard input.
132
133 * The new :option:`makemigrations --no-header` option avoids writing header
134 comments in generated migration file(s). This option is also available for
135 :djadmin:`squashmigrations`.
136
137 * :djadmin:`runserver` can now use `Watchman
138 <https://facebook.github.io/watchman/>`_ to improve the performance of
139 watching a large number of files for changes.
140
141 Migrations
142 ~~~~~~~~~~
143
144 * The new :option:`migrate --plan` option prints the list of migration
145 operations that will be performed.
146
147 * ``NoneType`` can now be serialized in migrations.
148
149 * You can now :ref:`register custom serializers <custom-migration-serializers>`
150 for migrations.
151
152 Models
153 ~~~~~~
154
155 * Added support for PostgreSQL operator classes (:attr:`.Index.opclasses`).
156
157 * Added support for partial indexes (:attr:`.Index.condition`).
158
159 * Added the :class:`~django.db.models.functions.NullIf` and
160 :class:`~django.db.models.functions.Reverse` database functions, as well as
161 many :ref:`math database functions <math-functions>`.
162
163 * Setting the new ``ignore_conflicts`` parameter of
164 :meth:`.QuerySet.bulk_create` to ``True`` tells the database to ignore
165 failure to insert rows that fail uniqueness constraints or other checks.
166
167 * The new :class:`~django.db.models.functions.ExtractIsoYear` function extracts
168 ISO-8601 week-numbering years from :class:`~django.db.models.DateField` and
169 :class:`~django.db.models.DateTimeField`, and the new :lookup:`iso_year`
170 lookup allows querying by an ISO-8601 week-numbering year.
171
172 * The new :meth:`.QuerySet.bulk_update` method allows efficiently updating
173 specific fields on multiple model instances.
174
175 * Django no longer always starts a transaction when a single query is being
176 performed, such as ``Model.save()``, ``QuerySet.update()``, and
177 ``Model.delete()``. This improves the performance of autocommit by reducing
178 the number of database round trips.
179
180 * Added SQLite support for the :class:`~django.db.models.StdDev` and
181 :class:`~django.db.models.Variance` functions.
182
183 * The handling of ``DISTINCT`` aggregation is added to the
184 :class:`~django.db.models.Aggregate` class. Adding :attr:`allow_distinct =
185 True <django.db.models.Aggregate.allow_distinct>` as a class attribute on
186 ``Aggregate`` subclasses allows a ``distinct`` keyword argument to be
187 specified on initialization to ensure that the aggregate function is only
188 called for each distinct value of ``expressions``.
189
190 * The :meth:`.RelatedManager.add`, :meth:`~.RelatedManager.create`,
191 :meth:`~.RelatedManager.remove`, :meth:`~.RelatedManager.set`,
192 ``get_or_create()``, and ``update_or_create()`` methods are now allowed on
193 many-to-many relationships with intermediate models. The new
194 ``through_defaults`` argument is used to specify values for new intermediate
195 model instance(s).
196
197 Requests and Responses
198 ~~~~~~~~~~~~~~~~~~~~~~
199
200 * Added :attr:`.HttpRequest.headers` to allow simple access to a request's
201 headers.
202
203 Serialization
204 ~~~~~~~~~~~~~
205
206 * You can now deserialize data using natural keys containing :ref:`forward
207 references <natural-keys-and-forward-references>` by passing
208 ``handle_forward_references=True`` to ``serializers.deserialize()``.
209 Additionally, :djadmin:`loaddata` handles forward references automatically.
210
211 Tests
212 ~~~~~
213
214 * The new :meth:`.SimpleTestCase.assertURLEqual` assertion checks for a given
215 URL, ignoring the ordering of the query string.
216 :meth:`~.SimpleTestCase.assertRedirects` uses the new assertion.
217
218 * The test :class:`~.django.test.Client` now supports automatic JSON
219 serialization of list and tuple ``data`` when
220 ``content_type='application/json'``.
221
222 * The new :setting:`ORACLE_MANAGED_FILES <TEST_ORACLE_MANAGED_FILES>` test
223 database setting allows using Oracle Managed Files (OMF) tablespaces.
224
225 * Deferrable database constraints are now checked at the end of each
226 :class:`~django.test.TestCase` test on SQLite 3.20+, just like on other
227 backends that support deferrable constraints. These checks aren't implemented
228 for older versions of SQLite because they would require expensive table
229 introspection there.
230
231 * :class:`~django.test.runner.DiscoverRunner` now skips the setup of databases
232 not :ref:`referenced by tests<testing-multi-db>`.
233
234 URLs
235 ~~~~
236
237 * The new :attr:`.ResolverMatch.route` attribute stores the route of the
238 matching URL pattern.
239
240 Validators
241 ~~~~~~~~~~
242
243 * :class:`.MaxValueValidator`, :class:`.MinValueValidator`,
244 :class:`.MinLengthValidator`, and :class:`.MaxLengthValidator` now accept
245 a callable ``limit_value``.
246
247 .. _backwards-incompatible-2.2:
248
249 Backwards incompatible changes in 2.2
250 =====================================
251
252 Database backend API
253 --------------------
254
255 This section describes changes that may be needed in third-party database
256 backends.
257
258 * Third-party database backends must implement support for table check
259 constraints or set ``DatabaseFeatures.supports_table_check_constraints`` to
260 ``False``.
261
262 * Third party database backends must implement support for ignoring
263 constraints or uniqueness errors while inserting or set
264 ``DatabaseFeatures.supports_ignore_conflicts`` to ``False``.
265
266 * Third party database backends must implement introspection for
267 ``DurationField`` or set ``DatabaseFeatures.can_introspect_duration_field``
268 to ``False``.
269
270 * ``DatabaseFeatures.uses_savepoints`` now defaults to ``True``.
271
272 * Third party database backends must implement support for partial indexes or
273 set ``DatabaseFeatures.supports_partial_indexes`` to ``False``.
274
275 * ``DatabaseIntrospection.table_name_converter()`` and
276 ``column_name_converter()`` are removed. Third party database backends may
277 need to instead implement ``DatabaseIntrospection.identifier_converter()``.
278 In that case, the constraint names that
279 ``DatabaseIntrospection.get_constraints()`` returns must be normalized by
280 ``identifier_converter()``.
281
282 * SQL generation for indexes is moved from :class:`~django.db.models.Index` to
283 ``SchemaEditor`` and these ``SchemaEditor`` methods are added:
284
285 * ``_create_primary_key_sql()`` and ``_delete_primary_key_sql()``
286 * ``_delete_index_sql()`` (to pair with ``_create_index_sql()``)
287 * ``_delete_unique_sql`` (to pair with ``_create_unique_sql()``)
288 * ``_delete_fk_sql()`` (to pair with ``_create_fk_sql()``)
289 * ``_create_check_sql()`` and ``_delete_check_sql()``
290
291 * The third argument of ``DatabaseWrapper.__init__()``,
292 ``allow_thread_sharing``, is removed.
293
294 Admin actions are no longer collected from base ``ModelAdmin`` classes
295 ----------------------------------------------------------------------
296
297 For example, in older versions of Django::
298
299 from django.contrib import admin
300
301
302 class BaseAdmin(admin.ModelAdmin):
303 actions = ["a"]
304
305
306 class SubAdmin(BaseAdmin):
307 actions = ["b"]
308
309 ``SubAdmin`` would have actions ``'a'`` and ``'b'``.
310
311 Now ``actions`` follows standard Python inheritance. To get the same result as
312 before::
313
314 class SubAdmin(BaseAdmin):
315 actions = BaseAdmin.actions + ["b"]
316
317 :mod:`django.contrib.gis`
318 -------------------------
319
320 * Support for GDAL 1.9 and 1.10 is dropped.
321
322 ``TransactionTestCase`` serialized data loading
323 -----------------------------------------------
324
325 Initial data migrations are now loaded in
326 :class:`~django.test.TransactionTestCase` at the end of the test, after the
327 database flush. In older versions, this data was loaded at the beginning of the
328 test, but this prevents the :option:`test --keepdb` option from working
329 properly (the database was empty at the end of the whole test suite). This
330 change shouldn't have an impact on your tests unless you've customized
331 :class:`~django.test.TransactionTestCase`'s internals.
332
333 ``sqlparse`` is required dependency
334 -----------------------------------
335
336 To simplify a few parts of Django's database handling, :pypi:`sqlparse 0.2.2+
337 <sqlparse>` is now a required dependency. It's automatically installed along
338 with Django.
339
340 ``cached_property`` aliases
341 ---------------------------
342
343 In usage like::
344
345 from django.utils.functional import cached_property
346
347
348 class A:
349 @cached_property
350 def base(self):
351 return ...
352
353 alias = base
354
355 ``alias`` is not cached. Where the problem can be detected (Python 3.6 and
356 later), such usage now raises ``TypeError: Cannot assign the same
357 cached_property to two different names ('base' and 'alias').``
358
359 Use this instead::
360
361 import operator
362
363
364 class A:
365 ...
366
367 alias = property(operator.attrgetter("base"))
368
369 Permissions for proxy models
370 ----------------------------
371
372 :ref:`Permissions for proxy models <proxy-models-permissions-topic>` are now
373 created using the content type of the proxy model rather than the content type
374 of the concrete model. A migration will update existing permissions when you
375 run :djadmin:`migrate`.
376
377 In the admin, the change is transparent for proxy models having the same
378 ``app_label`` as their concrete model. However, in older versions, users with
379 permissions for a proxy model with a *different* ``app_label`` than its
380 concrete model couldn't access the model in the admin. That's now fixed, but
381 you might want to audit the permissions assignments for such proxy models
382 (``[add|view|change|delete]_myproxy``) prior to upgrading to ensure the new
383 access is appropriate.
384
385 Finally, proxy model permission strings must be updated to use their own
386 ``app_label``. For example, for ``app.MyProxyModel`` inheriting from
387 ``other_app.ConcreteModel``, update
388 ``user.has_perm('other_app.add_myproxymodel')`` to
389 ``user.has_perm('app.add_myproxymodel')``.
390
391 Merging of form ``Media`` assets
392 --------------------------------
393
394 Form ``Media`` assets are now merged using a topological sort algorithm, as the
395 old pairwise merging algorithm is insufficient for some cases. CSS and
396 JavaScript files which don't include their dependencies may now be sorted
397 incorrectly (where the old algorithm produced results correctly by
398 coincidence).
399
400 Audit all ``Media`` classes for any missing dependencies. For example,
401 widgets depending on ``django.jQuery`` must specify
402 ``js=['admin/js/jquery.init.js', ...]`` when :ref:`declaring form media assets
403 <assets-as-a-static-definition>`.
404
405 Miscellaneous
406 -------------
407
408 * To improve readability, the ``UUIDField`` form field now displays values with
409 dashes, e.g. ``550e8400-e29b-41d4-a716-446655440000`` instead of
410 ``550e8400e29b41d4a716446655440000``.
411
412 * On SQLite, ``PositiveIntegerField`` and ``PositiveSmallIntegerField`` now
413 include a check constraint to prevent negative values in the database. If you
414 have existing invalid data and run a migration that recreates a table, you'll
415 see ``CHECK constraint failed``.
416
417 * For consistency with WSGI servers, the test client now sets the
418 ``Content-Length`` header to a string rather than an integer.
419
420 * The return value of :func:`django.utils.text.slugify` is no longer marked as
421 HTML safe.
422
423 * The default truncation character used by the :tfilter:`urlizetrunc`,
424 :tfilter:`truncatechars`, :tfilter:`truncatechars_html`,
425 :tfilter:`truncatewords`, and :tfilter:`truncatewords_html` template filters
426 is now the real ellipsis character (``…``) instead of 3 dots. You may have to
427 adapt some test output comparisons.
428
429 * Support for bytestring paths in the template filesystem loader is removed.
430
431 * :func:`django.utils.http.urlsafe_base64_encode` now returns a string instead
432 of a bytestring, and :func:`django.utils.http.urlsafe_base64_decode` may no
433 longer be passed a bytestring.
434
435 * Support for ``cx_Oracle`` < 6.0 is removed.
436
437 * The minimum supported version of ``mysqlclient`` is increased from 1.3.7 to
438 1.3.13.
439
440 * The minimum supported version of SQLite is increased from 3.7.15 to 3.8.3.
441
442 * In an attempt to provide more semantic query data, ``NullBooleanSelect`` now
443 renders ``<option>`` values of ``unknown``, ``true``, and ``false`` instead
444 of ``1``, ``2``, and ``3``. For backwards compatibility, the old values are
445 still accepted as data.
446
447 * :attr:`Group.name <django.contrib.auth.models.Group.name>` ``max_length``
448 is increased from 80 to 150 characters.
449
450 * Tests that violate deferrable database constraints now error when run on
451 SQLite 3.20+, just like on other backends that support such constraints.
452
453 * To catch usage mistakes, the test :class:`~django.test.Client` and
454 :func:`django.utils.http.urlencode` now raise ``TypeError`` if ``None`` is
455 passed as a value to encode because ``None`` can't be encoded in GET and POST
456 data. Either pass an empty string or omit the value.
457
458 * The ``ping_google`` management command now defaults to ``https``
459 instead of ``http`` for the sitemap's URL. If your site uses http, use the
460 new ``ping_google --sitemap-uses-http`` option. If you use the
461 ``django.contrib.sitemaps.ping_google`` function, set the new
462 ``sitemap_uses_https`` argument to ``False``.
463
464 * :djadmin:`runserver` no longer supports ``pyinotify`` (replaced by Watchman).
465
466 * The :class:`~django.db.models.Avg`, :class:`~django.db.models.StdDev`, and
467 :class:`~django.db.models.Variance` aggregate functions now return a
468 ``Decimal`` instead of a ``float`` when the input is ``Decimal``.
469
470 * Tests will fail on SQLite if apps without migrations have relations to apps
471 with migrations. This has been a documented restriction since migrations were
472 added in Django 1.7, but it fails more reliably now. You'll see tests failing
473 with errors like ``no such table: <app_label>_<model>``. This was observed
474 with several third-party apps that had models in tests without migrations.
475 You must add migrations for such models.
476
477 * Providing an integer in the ``key`` argument of the :meth:`.cache.delete` or
478 :meth:`.cache.get` now raises :exc:`ValueError`.
479
480 * Plural equations for some languages are changed, because the latest versions
481 from Transifex are incorporated.
482
483 .. note::
484
485 The ability to handle ``.po`` files containing different plural equations
486 for the same language was added in Django 2.2.12.
487
488 .. _deprecated-features-2.2:
489
490 Features deprecated in 2.2
491 ==========================
492
493 Model ``Meta.ordering`` will no longer affect ``GROUP BY`` queries
494 ------------------------------------------------------------------
495
496 A model's ``Meta.ordering`` affecting ``GROUP BY`` queries (such as
497 ``.annotate().values()``) is a common source of confusion. Such queries now
498 issue a deprecation warning with the advice to add an ``order_by()`` to retain
499 the current query. ``Meta.ordering`` will be ignored in such queries starting
500 in Django 3.1.
501
502 Miscellaneous
503 -------------
504
505 * ``django.utils.timezone.FixedOffset`` is deprecated in favor of
506 :class:`datetime.timezone`.
507
508 * The undocumented ``QuerySetPaginator`` alias of
509 ``django.core.paginator.Paginator`` is deprecated.
510
511 * The ``FloatRangeField`` model and form fields in ``django.contrib.postgres``
512 are deprecated in favor of a new name, ``DecimalRangeField``, to match the
513 underlying ``numrange`` data type used in the database.
514
515 * The ``FILE_CHARSET`` setting is deprecated. Starting with Django 3.1, files
516 read from disk must be UTF-8 encoded.
517
518 * ``django.contrib.staticfiles.storage.CachedStaticFilesStorage`` is
519 deprecated due to the intractable problems that it has. Use
520 :class:`.ManifestStaticFilesStorage` or a third-party cloud storage instead.
521
522 * :meth:`.RemoteUserBackend.configure_user` is now passed ``request`` as the
523 first positional argument, if it accepts it. Support for overrides that don't
524 accept it will be removed in Django 3.1.
525
526 * The ``SimpleTestCase.allow_database_queries``,
527 ``TransactionTestCase.multi_db``, and ``TestCase.multi_db``
528 attributes are deprecated in favor of :attr:`.SimpleTestCase.databases`,
529 :attr:`.TransactionTestCase.databases`, and :attr:`.TestCase.databases`.
530 These new attributes allow databases dependencies to be declared in order to
531 prevent unexpected queries against non-default databases to leak state
532 between tests. The previous behavior of ``allow_database_queries=True`` and
533 ``multi_db=True`` can be achieved by setting ``databases='__all__'``.