Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix AutoLastModifiedField default cache #521

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Unreleased
- Confirm support for `Django 4.0`
- Add Spanish translation
- Add French translation
- Fix AutoLastModifiedField cache (GH-#520)

4.2.0 (2021-10-11)
------------------
Expand Down
11 changes: 8 additions & 3 deletions model_utils/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.timezone import now

DEFAULT_CHOICES_NAME = 'STATUS'
Expand Down Expand Up @@ -34,9 +35,13 @@ class AutoLastModifiedField(AutoCreatedField):
"""
def get_default(self):
"""Return the default value for this field."""
if not hasattr(self, "_default"):
self._default = self._get_default()
return self._default
return self._get_default()

@cached_property
def _get_default(self):
if callable(self.default):
return self.default
return lambda: self.default

def pre_save(self, model_instance, add):
value = now()
Expand Down
9 changes: 9 additions & 0 deletions tests/test_models/test_timestamped_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ def test_modified(self):

self.assertEqual(t1.modified, datetime(2016, 1, 2))

def test_modified_is_not_cached(self):
with freeze_time(datetime(2016, 1, 1)):
t1 = TimeStamp()

with freeze_time(datetime(2017, 1, 1)):
t2 = TimeStamp()

self.assertNotEqual(t1.modified, t2.modified)

def test_overriding_created_via_object_creation_also_uses_creation_date_for_modified(self):
"""
Setting the created date when first creating an object
Expand Down