Ensure TimeStampedModel modified equals created on initial creation. (#319)

*  Ensure TimeStampedModel modified equals created on initial creation.

Add logic to AutoLastModifiedField which checks to see if the associated created field of the correct cField class type is also present. If the instance has not yet been saved (missing a pk), then set the value to modified to be equal to created.

Fixes #247

📚 Update changes and authors list related to changes.

* 🚑 Set TimeStampedModel modified to be equal to created during first save.

If instance does not yet have a pk, before defaulting the last modified to the current time, iterate over the the fields of the model, and instead use whatever value is found in the first occurance of the AutoCreatedField.

Fixes #247

* Move changelog up to unreleased section.
This commit is contained in:
Daniel Andrlik 2018-12-08 01:23:04 -05:00 committed by Asif Saif Uddin
parent b739f6fe87
commit 25743141bc
4 changed files with 15 additions and 0 deletions

View file

@ -47,3 +47,4 @@
| Radosław Jan Ganczarek <radoslaw@ganczarek.in>
| Lucas Wiman <lucas.wiman@gmail.com>
| Jack Cushman <jcushman@law.harvard.edu>
| Daniel Andrlik <daniel@andrlik.org>

View file

@ -6,6 +6,8 @@ master (unreleased)
- Fix handling of deferred attributes on Django 1.10+, fixes GH-278
- Fix `FieldTracker.has_changed()` and `FieldTracker.previous()` to return
correct responses for deferred fields.
- Update AutoLastModifiedField so that at instance creation it will
always be set equal to created to make querying easier. Fixes GH-254
- Support `reversed` for all kinds of `Choices` objects, fixes GH-309
- Fix Model instance non picklable GH-330

View file

@ -32,6 +32,11 @@ class AutoLastModifiedField(AutoCreatedField):
"""
def pre_save(self, model_instance, add):
value = now()
if not model_instance.pk:
for field in model_instance._meta.get_fields():
if isinstance(field, AutoCreatedField):
value = getattr(model_instance, field.name)
break
setattr(model_instance, self.attname, value)
return value

View file

@ -15,6 +15,13 @@ class TimeStampedModelTests(TestCase):
t1 = TimeStamp.objects.create()
self.assertEqual(t1.created, datetime(2016, 1, 1))
def test_created_sets_modified(self):
'''
Ensure that on creation that modifed is set exactly equal to created.
'''
t1 = TimeStamp.objects.create()
self.assertEqual(t1.created, t1.modified)
def test_modified(self):
with freeze_time(datetime(2016, 1, 1)):
t1 = TimeStamp.objects.create()