diff --git a/openwisp_controller/config/base/device.py b/openwisp_controller/config/base/device.py index d985ccaab..bcfff44ca 100644 --- a/openwisp_controller/config/base/device.py +++ b/openwisp_controller/config/base/device.py @@ -338,9 +338,9 @@ def _get_initial_values_for_checked_fields(self): if not present_values: return self.refresh_from_db(fields=present_values.keys()) - for field in self._changed_checked_fields: - setattr(self, f"_initial_{field}", field) - setattr(self, field, present_values[field]) + for field, value in present_values.items(): + setattr(self, f"_initial_{field}", getattr(self, field)) + setattr(self, field, value) def _check_name_changed(self): if self._initial_name == models.DEFERRED: diff --git a/openwisp_controller/config/tests/test_device.py b/openwisp_controller/config/tests/test_device.py index 9603606d3..d9bc3f59d 100644 --- a/openwisp_controller/config/tests/test_device.py +++ b/openwisp_controller/config/tests/test_device.py @@ -541,6 +541,20 @@ def test_changed_checked_fields_no_duplicates(self): device.__init__() self.assertEqual(device._changed_checked_fields.count("last_ip"), 1) + def test_deferred_fields_populated_correctly(self): + device = self._create_device( + name="deferred-test", + management_ip="10.0.0.1", + ) + # Load the instance with deferred fields omitted + device = Device.objects.only("id").get(pk=device.pk) + device.management_ip = "10.0.0.55" + # Saving the device object will populate the deferred fields + device.save() + # Ensure `_initial_` contains the actual value, not the field name + self.assertEqual(getattr(device, "_initial_management_ip"), "10.0.0.55") + self.assertNotEqual(getattr(device, "_initial_management_ip"), "management_ip") + def test_exceed_organization_device_limit(self): org = self._get_org() org.config_limits.device_limit = 1