Преглед изворни кода

Merge pull request #3899 from hSaria/3898-cable-str-pk

Fixes #3898: Call str of cable on delete to save PK in id_string
Jeremy Stretch пре 6 година
родитељ
комит
cf480375f6
3 измењених фајлова са 14 додато и 8 уклоњено
  1. 1 0
      docs/release-notes/version-2.6.md
  2. 9 7
      netbox/dcim/models.py
  3. 4 1
      netbox/dcim/tests/test_models.py

+ 1 - 0
docs/release-notes/version-2.6.md

@@ -29,6 +29,7 @@
 * [#3872](https://github.com/netbox-community/netbox/issues/3872) - Paginate related IPs of an address
 * [#3876](https://github.com/netbox-community/netbox/issues/3876) - Fixed min/max to ASN input field at the site creation page
 * [#3882](https://github.com/netbox-community/netbox/issues/3882) - Fix filtering of devices by rack group
+* [#3898](https://github.com/netbox-community/netbox/issues/3898) - Fix deleted message being set to None for cable 
 * [#3905](https://github.com/netbox-community/netbox/issues/3905) - Fix divide-by-zero on power feeds with low power values
 
 ---

+ 9 - 7
netbox/dcim/models.py

@@ -3027,15 +3027,14 @@ class Cable(ChangeLoggedModel):
             ('termination_b_type', 'termination_b_id'),
         )
 
-    def __str__(self):
-        if self.label:
-            return self.label
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
 
-        # Save a copy of the PK on the instance since it's nullified if .delete() is called
-        if not hasattr(self, 'id_string'):
-            self.id_string = '#{}'.format(self.pk)
+        # A copy of the PK to be used by __str__ in case the object is deleted
+        self._pk = self.pk
 
-        return self.id_string
+    def __str__(self):
+        return self.label or '#{}'.format(self._pk)
 
     def get_absolute_url(self):
         return reverse('dcim:cable', args=[self.pk])
@@ -3142,6 +3141,9 @@ class Cable(ChangeLoggedModel):
 
         super().save(*args, **kwargs)
 
+        # Update the private pk used in __str__ in case this is a new object (i.e. just got its pk)
+        self._pk = self.pk
+
     def to_csv(self):
         return (
             '{}.{}'.format(self.termination_a_type.app_label, self.termination_a_type.model),

+ 4 - 1
netbox/dcim/tests/test_models.py

@@ -325,9 +325,12 @@ class CableTestCase(TestCase):
 
     def test_cable_deletion(self):
         """
-        When a Cable is deleted, the `cable` field on its termination points must be nullified.
+        When a Cable is deleted, the `cable` field on its termination points must be nullified. The str() method
+        should still return the PK of the string even after being nullified.
         """
         self.cable.delete()
+        self.assertIsNone(self.cable.pk)
+        self.assertNotEqual(str(self.cable), '#None')
         interface1 = Interface.objects.get(pk=self.interface1.pk)
         self.assertIsNone(interface1.cable)
         interface2 = Interface.objects.get(pk=self.interface2.pk)