Просмотр исходного кода

Closes #23907: Defer conversion of IP values and dates to strings

REST API serializers now return IP values as netaddr objects, and dates
and times as native objects, so code that consumes serializer output
directly (such as restricted template rendering) can use them. A NetBox
JSON renderer converts them to strings exactly as before, so API
responses and the OpenAPI schema are unchanged. Event data and stored
background job results still receive strings.
Jeremy Stretch 16 часов назад
Родитель
Сommit
e3fa1536ca

+ 11 - 0
docs/plugins/development/rest-api.md

@@ -78,6 +78,17 @@ class MyModelSerializer(NetBoxModelSerializer):
 
 `RelatedObjectsField` renders each related object in its brief format, using the serializer for the related model. It lists only the objects the requesting user is permitted to view, and the viewset prefetches them automatically. (A serializer instantiated without a request in its context, such as in a script, lists every related object.)
 
+#### Native Values
+
+!!! info "This behavior was introduced in NetBox v4.8."
+
+Serializers return some values as native Python objects, which are converted to strings only when a response is rendered:
+
+* IP addresses and prefixes (e.g. from `ipam.api.field_serializers.IPAddressField`) are netaddr `IPNetwork` objects.
+* Dates and times (e.g. `created` and `last_updated`) are `date`, `datetime`, and `time` objects. This applies to every `DateField`, `DateTimeField`, and `TimeField` which doesn't set its own `format`, including those on plugin serializers.
+
+To encode serialized data outside of a response (e.g. with `json.dumps()`), use `utilities.json.APIJSONEncoder`.
+
 ## Viewsets
 
 Just as in the user interface, a REST API view handles the business logic of displaying and interacting with NetBox objects. NetBox provides the `NetBoxModelViewSet` class, which extends DRF's built-in `ModelViewSet` to handle bulk operations and object validation.

+ 11 - 11
netbox/dcim/tests/test_api.py

@@ -3498,7 +3498,7 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         response = self.client.get(f'{self._get_list_url()}?id={device.pk}', **self.header)
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
-        result = response.data['results'][0]
+        result = response.json()['results'][0]
         for field in ('primary_ip', 'primary_ip4'):
             self.assertEqual(result[field]['address'], str(nat_ip.address))
             self.assertEqual(result[field]['nat_inside']['address'], str(real_ip.address))
@@ -3525,10 +3525,10 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
         for field in ('primary_ip', 'primary_ip4'):
-            self.assertEqual(response.data[field]['address'], str(real_ip.address))
-            self.assertIsNone(response.data[field]['nat_inside'])
+            self.assertEqual(response.json()[field]['address'], str(real_ip.address))
+            self.assertIsNone(response.json()[field]['nat_inside'])
             self.assertCountEqual(
-                [ip['address'] for ip in response.data[field]['nat_outside']],
+                [ip['address'] for ip in response.json()[field]['nat_outside']],
                 [str(nat_ip.address)],
             )
 
@@ -3552,9 +3552,9 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         )
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
-        self.assertEqual(response.data['oob_ip']['address'], str(nat_ip.address))
-        self.assertEqual(response.data['oob_ip']['nat_inside']['address'], str(real_ip.address))
-        self.assertEqual(response.data['oob_ip']['nat_outside'], [])
+        self.assertEqual(response.json()['oob_ip']['address'], str(nat_ip.address))
+        self.assertEqual(response.json()['oob_ip']['nat_inside']['address'], str(real_ip.address))
+        self.assertEqual(response.json()['oob_ip']['nat_outside'], [])
 
     def test_get_object_includes_dns_name_on_primary_ip(self):
         device = create_test_device('dns-device')
@@ -7578,11 +7578,11 @@ class VirtualDeviceContextTestCase(APIViewTestCases.APIViewTestCase):
         response = self.client.get(self._get_detail_url(vdc), **self.header)
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
-        self.assertEqual(response.data['primary_ip4']['nat_inside']['address'], str(real_ip4.address))
-        self.assertEqual(response.data['primary_ip4']['nat_outside'], [])
-        self.assertIsNone(response.data['primary_ip6']['nat_inside'])
+        self.assertEqual(response.json()['primary_ip4']['nat_inside']['address'], str(real_ip4.address))
+        self.assertEqual(response.json()['primary_ip4']['nat_outside'], [])
+        self.assertIsNone(response.json()['primary_ip6']['nat_inside'])
         self.assertCountEqual(
-            [ip['address'] for ip in response.data['primary_ip6']['nat_outside']],
+            [ip['address'] for ip in response.json()['primary_ip6']['nat_outside']],
             [str(nat_ip6.address)],
         )
 

+ 1 - 2
netbox/extras/api/mixins.py

@@ -1,13 +1,12 @@
 from django.utils.translation import gettext_lazy as _
 from drf_spectacular.utils import OpenApiResponse, OpenApiTypes, extend_schema
 from rest_framework.decorators import action
-from rest_framework.renderers import JSONRenderer
 from rest_framework.response import Response
 from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
 
 from extras.models import ConfigTemplate
 from netbox.api.authentication import TokenWritePermission
-from netbox.api.renderers import TextRenderer
+from netbox.api.renderers import JSONRenderer, TextRenderer
 
 from .serializers import RenderConfigInputSerializer, RenderedConfigSerializer
 

+ 1 - 2
netbox/extras/api/views.py

@@ -8,7 +8,6 @@ from rest_framework.decorators import action
 from rest_framework.exceptions import PermissionDenied, ValidationError
 from rest_framework.generics import RetrieveUpdateDestroyAPIView
 from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin
-from rest_framework.renderers import JSONRenderer
 from rest_framework.response import Response
 from rest_framework.routers import APIRootView
 
@@ -20,7 +19,7 @@ from extras.scripts import EXEC_PARAM_FIELDS, prepare_script_form
 from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired, TokenWritePermission
 from netbox.api.features import SyncedDataMixin
 from netbox.api.metadata import ContentTypeMetadata
-from netbox.api.renderers import TextRenderer
+from netbox.api.renderers import JSONRenderer, TextRenderer
 from netbox.api.viewsets import BaseViewSet, NetBoxModelViewSet
 from netbox.api.viewsets.mixins import ObjectValidationMixin
 from users.models import Token

+ 3 - 1
netbox/extras/events.py

@@ -9,6 +9,7 @@ from core.events import *
 from core.models import ObjectType
 from netbox.models.features import has_feature
 from utilities.api import get_serializer_for_model
+from utilities.json import render_native_values
 from utilities.serialization import serialize_object
 
 from .conditions import AbsentData
@@ -80,7 +81,8 @@ def serialize_for_event(instance):
     }
     serializer = serializer_class(instance, context=serializer_context)
 
-    return serializer.data
+    # Conditions, webhooks and scripts receive native values (e.g. IP addresses) as they appear in the REST API
+    return render_native_values(serializer.data)
 
 
 def get_snapshots(instance, event_type):

+ 2 - 2
netbox/extras/models/models.py

@@ -16,7 +16,6 @@ from django.utils.html import escape
 from django.utils.safestring import mark_safe
 from django.utils.text import format_lazy
 from django.utils.translation import gettext_lazy as _
-from rest_framework.utils.encoders import JSONEncoder
 
 from extras.choices import *
 from extras.conditions import ConditionSet, InvalidCondition
@@ -41,6 +40,7 @@ from netbox.models.mixins import OwnerMixin
 from netbox.settings_utils import parse_job_timeout
 from utilities.html import clean_html
 from utilities.jinja2 import JINJA2_TEMPLATE_RE, render_jinja2, sanitize_http_header, validate_jinja2_syntax
+from utilities.json import APIJSONEncoder
 from utilities.querydict import dict_to_querydict
 from utilities.querysets import RestrictedQuerySet
 from utilities.tables import get_table_for_model
@@ -400,7 +400,7 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         """
         if self.body_template:
             return render_jinja2(self.body_template, context)
-        return json.dumps(context, cls=JSONEncoder)
+        return json.dumps(context, cls=APIJSONEncoder)
 
     def render_payload_url(self, context):
         """

+ 35 - 0
netbox/extras/tests/test_event_rules.py

@@ -13,6 +13,7 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
 from django.http import HttpResponse
 from django.test import RequestFactory, TestCase, override_settings, tag
 from django.urls import reverse
+from netaddr import IPNetwork
 from PIL import Image
 from requests import Session
 from rest_framework import status
@@ -190,6 +191,34 @@ class EventRuleTestCase(RQQueueTestMixin, APITestCase):
         # Evaluate the conditions (status='active')
         self.assertTrue(event_rule.eval_conditions(data))
 
+    def test_eventrule_conditions_native_values(self):
+        """
+        IP values, dates and times in event data are strings, as in the REST API, so conditions can compare them to
+        strings.
+        """
+        event_rule = EventRule(
+            name='Event Rule 1',
+            event_types=[OBJECT_CREATED],
+            conditions={'attr': 'address', 'value': '192.0.2.1/24'},
+        )
+        ip_address = IPAddress.objects.create(address='192.0.2.1/24')
+        data = serialize_for_event(ip_address)
+        self.assertEqual(data['address'], '192.0.2.1/24')
+        self.assertTrue(event_rule.eval_conditions(data))
+
+        # Nested representations are converted too
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        device = create_test_device('Device 1', site=site)
+        interface = Interface.objects.create(device=device, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED)
+        ip_address.assigned_object = interface
+        ip_address.save()
+        device.primary_ip4 = ip_address
+        device.save()
+        self.assertEqual(serialize_for_event(device)['primary_ip4']['address'], '192.0.2.1/24')
+
+        # So are dates and times
+        self.assertEqual(data['created'], ip_address.created.isoformat().replace('+00:00', 'Z'))
+
     def test_single_create_process_eventrule(self):
         """
         Check that creating an object with an applicable EventRule queues a background task for the rule's action.
@@ -1982,6 +2011,12 @@ class EventRuleNoObjectActionTestCase(TestCase):
 
 class WebhookRenderHeadersTest(TestCase):
 
+    def test_render_body_ip_values(self):
+        """The default request body renders IP values as strings."""
+        webhook = Webhook(name='Webhook 1', payload_url='http://localhost:9000/')
+        body = webhook.render_body({'data': {'address': IPNetwork('192.0.2.1/24')}})
+        self.assertEqual(json.loads(body), {'data': {'address': '192.0.2.1/24'}})
+
     def test_render_headers(self):
         """Basic header rendering with Jinja2 interpolation."""
         webhook = Webhook(

+ 4 - 2
netbox/ipam/api/field_serializers.py

@@ -25,7 +25,8 @@ class IPAddressField(serializers.CharField):
             raise serializers.ValidationError(e)
 
     def to_representation(self, value):
-        return str(value)
+        # Return the native value, which is rendered as a string (see netbox.api.renderers.JSONRenderer)
+        return value
 
 
 class IPNetworkField(serializers.CharField):
@@ -45,4 +46,5 @@ class IPNetworkField(serializers.CharField):
             raise serializers.ValidationError(e)
 
     def to_representation(self, value):
-        return str(value)
+        # Return the native value, which is rendered as a string (see netbox.api.renderers.JSONRenderer)
+        return value

+ 17 - 2
netbox/ipam/tests/test_api.py

@@ -1,3 +1,4 @@
+import datetime
 import json
 import logging
 from unittest.mock import patch
@@ -725,7 +726,7 @@ class PrefixTestCase(APIViewTestCases.APIViewTestCase):
             }
             response = self.client.post(url, data, format='json', **self.header)
             self.assertHttpStatus(response, status.HTTP_201_CREATED)
-            self.assertEqual(response.data['prefix'], prefixes_to_be_created[i])
+            self.assertEqual(response.json()['prefix'], prefixes_to_be_created[i])
             self.assertEqual(response.data['vrf']['id'], vrf.pk)
             self.assertEqual(response.data['description'], data['description'])
             # Verify that additional writable fields advertised by the schema are accepted and persisted
@@ -901,7 +902,7 @@ class PrefixTestCase(APIViewTestCases.APIViewTestCase):
         }
         response = self.client.post(url, data, format='json', **self.header)
         self.assertHttpStatus(response, status.HTTP_201_CREATED)
-        self.assertEqual(response.data['address'], '192.0.2.1/32')
+        self.assertEqual(response.json()['address'], '192.0.2.1/32')
         self.assertEqual(response.data['description'], data['description'])
 
         # Attempt to create an available IP with a prefix length less than its parent prefix
@@ -1174,6 +1175,20 @@ class IPAddressTestCase(APIViewTestCases.APIViewTestCase):
         )
         IPAddress.objects.bulk_create(ip_addresses)
 
+    def test_native_values_rendered_as_strings(self):
+        """
+        Serializers return IP values as netaddr objects, and dates and times as native objects, which are rendered as
+        strings.
+        """
+        ip_address = IPAddress.objects.first()
+        self.add_permissions('ipam.view_ipaddress')
+        response = self.client.get(self._get_detail_url(ip_address), **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertIsInstance(response.data['address'], IPNetwork)
+        self.assertEqual(response.json()['address'], str(ip_address.address))
+        self.assertIsInstance(response.data['created'], datetime.datetime)
+        self.assertEqual(response.json()['created'], ip_address.created.isoformat().replace('+00:00', 'Z'))
+
     @tag('regression')
     def test_create_with_invalid_address(self):
         """

+ 2 - 1
netbox/netbox/api/fields.py

@@ -161,7 +161,8 @@ class IPNetworkSerializer(serializers.Serializer):
     Representation of an IP network value (e.g. 192.0.2.0/24).
     """
     def to_representation(self, instance):
-        return str(instance)
+        # Return the native value, which is rendered as a string (see netbox.api.renderers.JSONRenderer)
+        return instance
 
     def to_internal_value(self, value):
         return IPNetwork(value)

+ 11 - 0
netbox/netbox/api/renderers.py

@@ -1,11 +1,22 @@
+from rest_framework import renderers
 from rest_framework.renderers import BaseRenderer, BrowsableAPIRenderer
 
+from utilities.json import APIJSONEncoder
+
 __all__ = (
     'FormlessBrowsableAPIRenderer',
+    'JSONRenderer',
     'TextRenderer',
 )
 
 
+class JSONRenderer(renderers.JSONRenderer):
+    """
+    Render JSON, including the native values (e.g. IP addresses) which serializers return.
+    """
+    encoder_class = APIJSONEncoder
+
+
 class FormlessBrowsableAPIRenderer(BrowsableAPIRenderer):
     """
     Override the built-in BrowsableAPIRenderer to disable HTML forms.

+ 2 - 1
netbox/netbox/jobs.py

@@ -27,6 +27,7 @@ from core.models import Job, ObjectType
 from netbox.constants import ADVISORY_LOCK_KEYS
 from netbox.registry import registry
 from utilities.exceptions import AbortRequest
+from utilities.json import render_native_values
 from utilities.request import apply_request_processors
 
 __all__ = (
@@ -440,7 +441,7 @@ class AsyncAPIJob(JobRunner):
         # success and failure.
         self.job.data = {
             'status_code': response.status_code,
-            'data': response.data,
+            'data': render_native_values(response.data),
         }
 
         if response.status_code >= 400:

+ 5 - 1
netbox/netbox/settings.py

@@ -831,6 +831,10 @@ REST_FRAMEWORK_VERSION = '.'.join(RELEASE.version.split('-')[0].split('.')[:2])
 REST_FRAMEWORK = {
     'ALLOWED_VERSIONS': [REST_FRAMEWORK_VERSION],
     'COERCE_DECIMAL_TO_STRING': False,
+    # Serializers return native dates and times, which are rendered as strings (see utilities.json.APIJSONEncoder)
+    'DATE_FORMAT': None,
+    'DATETIME_FORMAT': None,
+    'TIME_FORMAT': None,
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.SessionAuthentication',
         'netbox.api.authentication.TokenAuthentication',
@@ -849,7 +853,7 @@ REST_FRAMEWORK = {
         'netbox.api.authentication.TokenPermissions',
     ),
     'DEFAULT_RENDERER_CLASSES': (
-        'rest_framework.renderers.JSONRenderer',
+        'netbox.api.renderers.JSONRenderer',
         'netbox.api.renderers.FormlessBrowsableAPIRenderer',
     ),
     'DEFAULT_SCHEMA_CLASS': 'core.api.schema.NetBoxAutoSchema',

+ 1 - 1
netbox/netbox/tests/test_api.py

@@ -825,7 +825,7 @@ class IncludeFieldsTestCase(APITestCase):
     def get(self, url, status_code=status.HTTP_200_OK):
         response = self.client.get(url, **self.header)
         self.assertHttpStatus(response, status_code)
-        return response.data
+        return response.json()
 
     def test_include_optional_field(self):
         self.add_permissions('dcim.view_device', 'dcim.view_interface')

+ 15 - 0
netbox/netbox/tests/test_api_background.py

@@ -106,6 +106,21 @@ class BackgroundBulkWriteTests(RQQueueTestMixin, APITestCase):
         for obj in job.data['data']:
             self.assertTrue(obj['url'].startswith('http://testserver/'), obj['url'])
 
+    def test_background_bulk_create_ip_values(self):
+        """
+        IP values in the result captured on the job are stored as strings, as they appear in the response.
+        """
+        self.add_permissions('ipam.add_ipaddress', 'ipam.view_ipaddress')
+        payload = [{'address': '192.0.2.1/24'}, {'address': '192.0.2.2/24'}]
+        response = self.client.post(
+            '/api/ipam/ip-addresses/?background=true', payload, format='json', **self.header
+        )
+        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
+        job = Job.objects.get(pk=response.data['job']['id'])
+        self.assertEqual(job.status, JobStatusChoices.STATUS_COMPLETED)
+        job.refresh_from_db()
+        self.assertEqual([obj['address'] for obj in job.data['data']], ['192.0.2.1/24', '192.0.2.2/24'])
+
     def test_background_bulk_create_invalid_deferred(self):
         # Validation is deferred to the worker: an invalid bulk create is accepted with 202 and
         # fails at execution time (capturing the 400 in job.data), rather than being rejected

+ 1 - 1
netbox/users/tests/test_api.py

@@ -279,7 +279,7 @@ class TokenTestCase(
         self.assertIn('token', response.data)
         self.assertEqual(len(response.data['token']), TOKEN_DEFAULT_LENGTH)
         self.assertEqual(response.data['description'], data['description'])
-        self.assertEqual(response.data['expires'], data['expires'])
+        self.assertEqual(response.json()['expires'], data['expires'])
         token = Token.objects.get(user=user)
         self.assertEqual(token.key, response.data['key'])
         self.assertEqual(token.enabled, response.data['enabled'])

+ 50 - 0
netbox/utilities/json.py

@@ -1,16 +1,66 @@
+import datetime
 import decimal
 import json
 
 from django.core.serializers.json import DjangoJSONEncoder
+from netaddr import IPAddress, IPNetwork
+from rest_framework import ISO_8601, serializers
+from rest_framework.utils.encoders import JSONEncoder
 
 from utilities.datetime import datetime_from_timestamp
 
 __all__ = (
+    'API_NATIVE_VALUE_RENDERERS',
+    'APIJSONEncoder',
     'ConfigJSONEncoder',
     'CustomFieldJSONEncoder',
     'JobLogDecoder',
+    'render_native_values',
 )
 
+# Native values which REST API serializers return, mapped to the functions which render them for a response
+# (datetime precedes date, its base class.) Dates and times are rendered by REST framework's own fields, in the current
+# time zone.
+API_NATIVE_VALUE_RENDERERS = {
+    IPAddress: str,
+    IPNetwork: str,
+    datetime.datetime: serializers.DateTimeField(format=ISO_8601).to_representation,
+    datetime.date: serializers.DateField(format=ISO_8601).to_representation,
+    datetime.time: serializers.TimeField(format=ISO_8601).to_representation,
+}
+
+
+def _get_native_value_renderer(value):
+    for value_type, renderer in API_NATIVE_VALUE_RENDERERS.items():
+        if isinstance(value, value_type):
+            return renderer
+    return None
+
+
+def render_native_values(data):
+    """
+    Return a copy of serialized data with its native values (e.g. IP addresses) rendered as they appear in REST API
+    responses. Other values are unchanged.
+    """
+    if renderer := _get_native_value_renderer(data):
+        return renderer(data)
+    if isinstance(data, dict):
+        return {key: render_native_values(value) for key, value in data.items()}
+    if isinstance(data, (list, tuple)):
+        return [render_native_values(item) for item in data]
+    return data
+
+
+class APIJSONEncoder(JSONEncoder):
+    """
+    Extend REST framework's JSON encoder to render the native values which serializers return (see
+    API_NATIVE_VALUE_RENDERERS).
+    """
+    def default(self, obj):
+        if renderer := _get_native_value_renderer(obj):
+            return renderer(obj)
+        return super().default(obj)
+
 
 class CustomFieldJSONEncoder(DjangoJSONEncoder):
     """

+ 61 - 0
netbox/utilities/tests/test_json.py

@@ -0,0 +1,61 @@
+import datetime
+import json
+from decimal import Decimal
+
+from django.test import SimpleTestCase, override_settings
+from netaddr import IPAddress, IPNetwork
+
+from utilities.json import APIJSONEncoder, render_native_values
+
+
+class APIJSONEncoderTest(SimpleTestCase):
+
+    def test_ip_values(self):
+        data = {'address': IPNetwork('192.0.2.1/24'), 'gateway': IPAddress('192.0.2.254'), 'amount': Decimal('1.5')}
+        self.assertEqual(
+            json.loads(json.dumps(data, cls=APIJSONEncoder)),
+            {'address': '192.0.2.1/24', 'gateway': '192.0.2.254', 'amount': 1.5},
+        )
+
+    def test_dates_and_times(self):
+        """
+        Dates and times are rendered as REST framework's fields render them, in the current time zone.
+        """
+        data = {
+            'datetime': datetime.datetime(2026, 12, 5, 14, 30, 1, 123456, tzinfo=datetime.UTC),
+            'date': datetime.date(2026, 12, 5),
+            'time': datetime.time(14, 30, 1, 250000),
+        }
+        cases = (
+            ('UTC', '2026-12-05T14:30:01.123456Z'),
+            ('Asia/Kolkata', '2026-12-05T20:00:01.123456+05:30'),
+        )
+        for time_zone, expected in cases:
+            with self.subTest(time_zone=time_zone), override_settings(TIME_ZONE=time_zone):
+                self.assertEqual(
+                    json.loads(json.dumps(data, cls=APIJSONEncoder)),
+                    {'datetime': expected, 'date': '2026-12-05', 'time': '14:30:01.250000'},
+                )
+
+
+class RenderNativeValuesTest(SimpleTestCase):
+
+    def test_nested_values(self):
+        data = {
+            'address': IPNetwork('192.0.2.1/24'),
+            'primary_ip': {'id': 1, 'address': IPNetwork('2001:db8::1/64')},
+            'allowed_ips': [IPNetwork('198.51.100.0/24')],
+            'gateways': (IPAddress('192.0.2.254'),),
+            'name': 'Device 1',
+            'weight': Decimal('1.5'),
+            'created': datetime.datetime(2026, 12, 5, 14, 30, tzinfo=datetime.UTC),
+        }
+        self.assertEqual(render_native_values(data), {
+            'address': '192.0.2.1/24',
+            'primary_ip': {'id': 1, 'address': '2001:db8::1/64'},
+            'allowed_ips': ['198.51.100.0/24'],
+            'gateways': ['192.0.2.254'],
+            'name': 'Device 1',
+            'weight': Decimal('1.5'),
+            'created': '2026-12-05T14:30:00Z',
+        })

+ 4 - 4
netbox/virtualization/tests/test_api.py

@@ -679,7 +679,7 @@ class VirtualMachineTestCase(APIViewTestCases.APIViewTestCase):
         response = self.client.get(f'{self._get_list_url()}?id={virtualmachine.pk}', **self.header)
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
-        result = response.data['results'][0]
+        result = response.json()['results'][0]
         for field in ('primary_ip', 'primary_ip4'):
             self.assertEqual(result[field]['address'], str(nat_ip.address))
             self.assertEqual(result[field]['nat_inside']['address'], str(real_ip.address))
@@ -706,10 +706,10 @@ class VirtualMachineTestCase(APIViewTestCases.APIViewTestCase):
         self.assertHttpStatus(response, status.HTTP_200_OK)
 
         for field in ('primary_ip', 'primary_ip4'):
-            self.assertEqual(response.data[field]['address'], str(real_ip.address))
-            self.assertIsNone(response.data[field]['nat_inside'])
+            self.assertEqual(response.json()[field]['address'], str(real_ip.address))
+            self.assertIsNone(response.json()[field]['nat_inside'])
             self.assertCountEqual(
-                [ip['address'] for ip in response.data[field]['nat_outside']],
+                [ip['address'] for ip in response.json()[field]['nat_outside']],
                 [str(nat_ip.address)],
             )