feat(monitor): Change default to None when the field is marked as nullable and no default is provided (#599)

This commit is contained in:
Guilherme Martins Crocetti 2024-04-04 05:26:17 -03:00 committed by GitHub
parent 714632e8bf
commit 4c9d6eee13
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 13 additions and 22 deletions

View file

@ -3,6 +3,8 @@ Changelog
To be released
--------------
- Remove MonitorField deprecation warning. `None` - instead of
`django.utils.timezone.now` will be used when nullable and no default provided (GH-#599)
- 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)

View file

@ -1,6 +1,5 @@
import secrets
import uuid
import warnings
from django.conf import settings
from django.core.exceptions import ValidationError
@ -107,17 +106,8 @@ class MonitorField(models.DateTimeField):
"""
def __init__(self, *args, monitor, when=None, **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)
default = None if kwargs.get("null") else now
kwargs.setdefault('default', default)
self.monitor = monitor
if when is not None:
when = set(when)

View file

@ -98,6 +98,7 @@ class TimeFrameManagerAdded(TimeFramedModel):
class Monitored(models.Model):
name = models.CharField(max_length=25)
name_changed = MonitorField(monitor="name")
name_changed_nullable = MonitorField(monitor="name", null=True)
class MonitorWhen(models.Model):

View file

@ -34,17 +34,15 @@ 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__)
def test_monitor_default_is_none_when_nullable(self):
self.assertIsNone(self.instance.name_changed_nullable)
expected_datetime = datetime(2022, 1, 18, 12, 0, 0, tzinfo=timezone.utc)
with self.assertWarns(DeprecationWarning, msg=warning_message):
MonitorField(monitor="foo", null=True, default=None)
self.instance.name = "Jose"
with time_machine.travel(expected_datetime, tick=False):
self.instance.save()
self.assertEqual(self.instance.name_changed_nullable, expected_datetime)
class MonitorWhenFieldTests(TestCase):