From 22015b8e69ffc707c10ae30b41b1ee1ae2778a49 Mon Sep 17 00:00:00 2001 From: Guilherme Martins Crocetti <24530683+gmcrocetti@users.noreply.github.com> Date: Wed, 19 Jul 2023 19:39:36 -0300 Subject: [PATCH] chore(monitor-field): Add deprecation warning when the field is null and no default is provided. The new behavior will be introduced in a next major release --- CHANGES.rst | 2 ++ model_utils/fields.py | 11 +++++++++++ tests/test_fields/test_monitor_field.py | 12 ++++++++++++ 3 files changed, 25 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 87422fd..e5e48e5 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -3,6 +3,8 @@ Changelog To be released -------------- +- Add deprecation warning for MonitorField. The default value will be `None` + instead of `django.utils.timezone.now` - when nullable and without a default. - Add Brazilian Portuguese translation (GH-#578) - Don't use `post_init` signal for initialize tracker diff --git a/model_utils/fields.py b/model_utils/fields.py index ce05e9f..e04ada2 100644 --- a/model_utils/fields.py +++ b/model_utils/fields.py @@ -1,5 +1,6 @@ import secrets import uuid +import warnings from collections.abc import Callable from django.conf import settings @@ -107,6 +108,16 @@ class MonitorField(models.DateTimeField): """ def __init__(self, *args, **kwargs): + if kwargs.get("null") and kwargs.get("default") is None: + warning_message = ( + "{}.default is set to 'django.utils.timezone.now' - when nullable" + " and no default. This behavior will be deprecated in the next" + " major release in favor of 'None'. See" + " https://django-model-utils.readthedocs.io/en/stable/fields.html" + "#monitorfield for more information." + ).format(self.__class__.__name__) + warnings.warn(warning_message, DeprecationWarning) + kwargs.setdefault('default', now) monitor = kwargs.pop('monitor', None) if not monitor: diff --git a/tests/test_fields/test_monitor_field.py b/tests/test_fields/test_monitor_field.py index cca6762..d1c00db 100644 --- a/tests/test_fields/test_monitor_field.py +++ b/tests/test_fields/test_monitor_field.py @@ -34,6 +34,18 @@ class MonitorFieldTests(TestCase): with self.assertRaises(TypeError): MonitorField() + def test_nullable_without_default_deprecation(self): + warning_message = ( + "{}.default is set to 'django.utils.timezone.now' - when nullable" + " and no default. This behavior will be deprecated in the next" + " major release in favor of 'None'. See" + " https://django-model-utils.readthedocs.io/en/stable/fields.html" + "#monitorfield for more information." + ).format(MonitorField.__name__) + + with self.assertWarns(DeprecationWarning, msg=warning_message): + MonitorField(monitor="foo", null=True, default=None) + class MonitorWhenFieldTests(TestCase): """