Add status_changed field to upload_fields parameter during save if status field is present (#441)

* implementation/tests

* naming problem
This commit is contained in:
H. Buğra Aydın 2020-09-17 17:34:57 +03:00 committed by GitHub
parent b7770165d5
commit 2ad67e77b1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 48 additions and 0 deletions

View file

@ -15,6 +15,7 @@
| Bo Marchman <bo.marchman@gmail.com>
| Bojan Mihelac <bmihelac@mihelac.org>
| Bruno Alla <bruno.alla@founders4schools.org.uk>
| Bugra Aydin <bugraaydin.cs@gmail.com>
| Craig Anderson <craiga@craiga.id.au>
| Daniel Andrlik <daniel@andrlik.org>
| Daniel Stanton <stringsonfire@me.com>

View file

@ -13,6 +13,9 @@ CHANGES
- Add available_objects manager to SoftDeletableModel and add deprecation
warning to objects manager.
- Add support for `Django 3.1`
- StatusModel now automatically adds 'status_changed' field during save as an
update_fieldsparameter when 'status' is present in it to make sure it is not
forgotten.
4.0.0 (2019-12-11)
------------------

View file

@ -67,6 +67,20 @@ class StatusModel(models.Model):
status = StatusField(_('status'))
status_changed = MonitorField(_('status changed'), monitor='status')
def save(self, *args, **kwargs):
"""
Overriding the save method in order to make sure that
status_changed field is updated even if it is not given as
a parameter to the update field argument.
"""
if (
'update_fields' in kwargs
and 'status' in kwargs['update_fields']
and 'status_changed' not in kwargs['update_fields']
):
kwargs['update_fields'] += ['status_changed']
super().save(*args, **kwargs)
class Meta:
abstract = True

View file

@ -38,6 +38,36 @@ class StatusModelTests(TestCase):
t1.save()
self.assertTrue(t1.status_changed > date_active_again)
def test_save_with_update_fields_overrides_status_changed_provided(self):
'''
Tests if the save method updated status_changed field
accordingly when update_fields is used as an argument
and status_changed is provided
'''
with freeze_time(datetime(2020,1,1)):
t1 = Status.objects.create()
with freeze_time(datetime(2020,1,2)):
t1.status = Status.on_hold
t1.save(update_fields=['status', 'status_changed'])
self.assertEqual(t1.status_changed, datetime(2020,1,2))
def test_save_with_update_fields_overrides_status_changed_not_provided(self):
'''
Tests if the save method updated status_changed field
accordingly when update_fields is used as an argument
with status and status_changed is not provided
'''
with freeze_time(datetime(2020,1,1)):
t1 = Status.objects.create()
with freeze_time(datetime(2020,1,2)):
t1.status = Status.on_hold
t1.save(update_fields=['status'])
self.assertEqual(t1.status_changed, datetime(2020,1,2))
class StatusModelPlainTupleTests(StatusModelTests):
def setUp(self):