ソースを参照

Fixes #23818: Break ties in non-unique default orderings

Thirteen models and the tagged objects endpoint ordered their results
by fields that can repeat, so offset pagination could return an object
twice and skip another. Each of these orderings now ends with the
primary key, and the indexes that serve them include it as well.
Martin Hauser 21 時間 前
親
コミット
81becab0e9

+ 55 - 0
netbox/dcim/migrations/0252_default_ordering_tiebreakers.py

@@ -0,0 +1,55 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('dcim', '0251_fix_ltree_cascade_triggers'),
+        ('extras', '0145_taggeditem_object_id_bigint'),
+        ('ipam', '0097_merge_ipaddress_host_index_and_multi_protocol_services'),
+        ('tenancy', '0027_fix_ltree_cascade_triggers'),
+        ('users', '0016_default_ordering_indexes'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='inventoryitemtemplate',
+            options={'ordering': ('device_type__id', 'parent__id', 'name', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='platform',
+            options={'ordering': ('sort_path', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='virtualchassis',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='virtualdevicecontext',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.RemoveIndex(
+            model_name='platform',
+            name='dcim_platform_sort_path_idx',
+        ),
+        migrations.RemoveIndex(
+            model_name='virtualchassis',
+            name='dcim_virtua_name_2dc5cd_idx',
+        ),
+        migrations.RemoveIndex(
+            model_name='virtualdevicecontext',
+            name='dcim_virtua_name_079d4d_idx',
+        ),
+        migrations.AddIndex(
+            model_name='platform',
+            index=models.Index(fields=['sort_path', 'id'], name='dcim_platform_sort_path_idx'),
+        ),
+        migrations.AddIndex(
+            model_name='virtualchassis',
+            index=models.Index(fields=['name', 'id'], name='dcim_virtua_name_02e36c_idx'),
+        ),
+        migrations.AddIndex(
+            model_name='virtualdevicecontext',
+            index=models.Index(fields=['name', 'id'], name='dcim_virtua_name_332875_idx'),
+        ),
+    ]

+ 1 - 1
netbox/dcim/models/device_component_templates.py

@@ -1078,7 +1078,7 @@ class InventoryItemTemplate(LtreeModel, ComponentTemplateModel):
     component_model = InventoryItem
     component_model = InventoryItem
 
 
     class Meta:
     class Meta:
-        ordering = ('device_type__id', 'parent__id', 'name')
+        ordering = ('device_type__id', 'parent__id', 'name', 'pk')  # (device_type, parent, name) may be non-unique
         indexes = (
         indexes = (
             models.Index(fields=('component_type', 'component_id')),
             models.Index(fields=('component_type', 'component_id')),
             GistIndex(fields=['path'], name='dcim_inv_item_tmpl_path_gist'),
             GistIndex(fields=['path'], name='dcim_inv_item_tmpl_path_gist'),

+ 6 - 6
netbox/dcim/models/devices.py

@@ -505,10 +505,10 @@ class Platform(NestedLtreeGroupModel):
     clone_fields = ('parent', 'description')
     clone_fields = ('parent', 'description')
 
 
     class Meta:
     class Meta:
-        ordering = ('sort_path',)
+        ordering = ('sort_path', 'pk')  # sort_path may be non-unique
         indexes = (
         indexes = (
             GistIndex(fields=['path'], name='dcim_platform_path_gist'),
             GistIndex(fields=['path'], name='dcim_platform_path_gist'),
-            models.Index(fields=['sort_path'], name='dcim_platform_sort_path_idx'),
+            models.Index(fields=['sort_path', 'id'], name='dcim_platform_sort_path_idx'),
         )
         )
         verbose_name = _('platform')
         verbose_name = _('platform')
         verbose_name_plural = _('platforms')
         verbose_name_plural = _('platforms')
@@ -1338,9 +1338,9 @@ class VirtualChassis(PrimaryModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('virtual chassis')
         verbose_name = _('virtual chassis')
         verbose_name_plural = _('virtual chassis')
         verbose_name_plural = _('virtual chassis')
@@ -1445,7 +1445,7 @@ class VirtualDeviceContext(PrimaryModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
                 fields=('device', 'identifier',),
                 fields=('device', 'identifier',),
@@ -1457,7 +1457,7 @@ class VirtualDeviceContext(PrimaryModel):
             ),
             ),
         )
         )
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('virtual device context')
         verbose_name = _('virtual device context')
         verbose_name_plural = _('virtual device contexts')
         verbose_name_plural = _('virtual device contexts')

+ 71 - 0
netbox/dcim/tests/test_models.py

@@ -828,6 +828,28 @@ class RackTestCase(TestCase):
         self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
         self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
 
 
 
 
+class PlatformTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Root platforms sharing a name are paginated once each, in name and then primary key order.
+        """
+        manufacturers = Manufacturer.objects.bulk_create(
+            Manufacturer(name=f'Manufacturer {i}', slug=f'manufacturer-{i}') for i in range(4)
+        )
+        Platform.objects.bulk_create(
+            Platform(name=f'Platform {i}', slug=f'platform-{i}', manufacturer=manufacturer)
+            for manufacturer in manufacturers for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(Platform.objects.all(), key=lambda obj: (obj.sort_path, obj.pk))]
+
+        queryset = Platform.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
+
 class DeviceTestCase(TestCase):
 class DeviceTestCase(TestCase):
 
 
     @classmethod
     @classmethod
@@ -3948,6 +3970,19 @@ class VirtualDeviceContextTestCase(TestCase):
                 self.assertIn(field, cm.exception.message_dict)
                 self.assertIn(field, cm.exception.message_dict)
                 self.assertIn('must belong to an interface', str(cm.exception.message_dict[field]))
                 self.assertIn('must belong to an interface', str(cm.exception.message_dict[field]))
 
 
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """Virtual device contexts sharing a name are paginated once each, in name and then primary key order."""
+        VirtualDeviceContext.objects.bulk_create(
+            VirtualDeviceContext(name=f'VDC {i}', status='active') for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(VirtualDeviceContext.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = VirtualDeviceContext.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
 
 
 class VirtualChassisTestCase(TestCase):
 class VirtualChassisTestCase(TestCase):
 
 
@@ -4198,6 +4233,21 @@ class VirtualChassisTestCase(TestCase):
         with self.assertRaises(ValidationError):
         with self.assertRaises(ValidationError):
             device2.full_clean()
             device2.full_clean()
 
 
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Virtual chassis sharing a name are paginated once each, in name and then primary key order.
+        """
+        VirtualChassis.objects.bulk_create(
+            VirtualChassis(name=f'Virtual Chassis {i}') for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(VirtualChassis.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = VirtualChassis.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
 
 
 class VCPositionTokenTestCase(TestCase):
 class VCPositionTokenTestCase(TestCase):
 
 
@@ -4703,6 +4753,27 @@ class InventoryItemCycleTestCase(TestCase):
             a.full_clean()
             a.full_clean()
 
 
 
 
+class InventoryItemTemplateTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Root inventory item templates sharing a name are paginated once each, in name and then primary key order.
+        """
+        manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+        device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
+        InventoryItemTemplate.objects.bulk_create(
+            InventoryItemTemplate(device_type=device_type, name=f'Inventory Item {i}')
+            for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(InventoryItemTemplate.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = InventoryItemTemplate.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
+
 class InventoryItemTemplateCycleTestCase(TestCase):
 class InventoryItemTemplateCycleTestCase(TestCase):
     """InventoryItemTemplate must likewise reject self/descendant as parent."""
     """InventoryItemTemplate must likewise reject self/descendant as parent."""
 
 

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

@@ -191,7 +191,7 @@ class TagViewSet(NetBoxModelViewSet):
 class TaggedItemViewSet(RetrieveModelMixin, ListModelMixin, BaseViewSet):
 class TaggedItemViewSet(RetrieveModelMixin, ListModelMixin, BaseViewSet):
     queryset = TaggedItem.objects.prefetch_related(
     queryset = TaggedItem.objects.prefetch_related(
         'content_type', 'content_object', 'tag'
         'content_type', 'content_object', 'tag'
-    ).order_by('tag__weight', 'tag__name')
+    ).order_by('tag__weight', 'tag__name', 'pk')
     serializer_class = serializers.TaggedItemSerializer
     serializer_class = serializers.TaggedItemSerializer
     filterset_class = filtersets.TaggedItemFilterSet
     filterset_class = filtersets.TaggedItemFilterSet
 
 

+ 52 - 0
netbox/extras/migrations/0146_default_ordering_tiebreakers.py

@@ -0,0 +1,52 @@
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('contenttypes', '0002_remove_content_type_name'),
+        ('core', '0026_populate_job_execution_time'),
+        ('extras', '0145_taggeditem_object_id_bigint'),
+        ('users', '0016_default_ordering_indexes'),
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='configtemplate',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='exporttemplate',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='tableconfig',
+            options={'ordering': ('weight', 'name', 'pk')},
+        ),
+        migrations.RemoveIndex(
+            model_name='configtemplate',
+            name='extras_conf_name_e276bf_idx',
+        ),
+        migrations.RemoveIndex(
+            model_name='exporttemplate',
+            name='extras_expo_name_55a9af_idx',
+        ),
+        migrations.RemoveIndex(
+            model_name='tableconfig',
+            name='extras_tabl_weight_7c4bb6_idx',
+        ),
+        migrations.AddIndex(
+            model_name='configtemplate',
+            index=models.Index(fields=['name', 'id'], name='extras_conf_name_ede402_idx'),
+        ),
+        migrations.AddIndex(
+            model_name='exporttemplate',
+            index=models.Index(fields=['name', 'id'], name='extras_expo_name_1ffcf7_idx'),
+        ),
+        migrations.AddIndex(
+            model_name='tableconfig',
+            index=models.Index(fields=['weight', 'name', 'id'], name='extras_tabl_weight_530e33_idx'),
+        ),
+    ]

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

@@ -453,9 +453,9 @@ class ConfigTemplate(
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ('name',)
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('config template')
         verbose_name = _('config template')
         verbose_name_plural = _('config templates')
         verbose_name_plural = _('config templates')

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

@@ -540,9 +540,9 @@ class ExportTemplate(
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ('name',)
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('export template')
         verbose_name = _('export template')
         verbose_name_plural = _('export templates')
         verbose_name_plural = _('export templates')
@@ -721,9 +721,9 @@ class TableConfig(CloningMixin, ChangeLoggedModel):
     clone_fields = ('object_type', 'table', 'enabled', 'shared', 'columns', 'ordering')
     clone_fields = ('object_type', 'table', 'enabled', 'shared', 'columns', 'ordering')
 
 
     class Meta:
     class Meta:
-        ordering = ('weight', 'name')
+        ordering = ('weight', 'name', 'pk')  # (weight, name) may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('weight', 'name')),  # Default ordering
+            models.Index(fields=('weight', 'name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('table config')
         verbose_name = _('table config')
         verbose_name_plural = _('table configs')
         verbose_name_plural = _('table configs')

+ 25 - 0
netbox/extras/tests/test_api.py

@@ -33,6 +33,7 @@ from dcim.models import (
     Site,
     Site,
 )
 )
 from extras.api.serializers import EventRuleSerializer, ScriptSerializer
 from extras.api.serializers import EventRuleSerializer, ScriptSerializer
+from extras.api.views import TaggedItemViewSet
 from extras.choices import *
 from extras.choices import *
 from extras.models import *
 from extras.models import *
 from extras.scripts import BooleanVar, IntegerVar, MultiObjectVar, ObjectVar, StringVar
 from extras.scripts import BooleanVar, IntegerVar, MultiObjectVar, ObjectVar, StringVar
@@ -1437,6 +1438,30 @@ class TaggedItemTestCase(
         for item in results.values():
         for item in results.values():
             self.assertEqual(item['object']['id'], item['object_id'])
             self.assertEqual(item['object']['id'], item['object_id'])
 
 
+    @tag('regression')  # Ref: #23818
+    def test_list_objects_duplicate_tag_pagination(self):
+        """Tagged items sharing a tag are listed once each across pages, in tag and then primary key order."""
+        self.add_permissions('extras.view_taggeditem')
+        # Weight order differs from name order
+        Tag.objects.filter(slug='tag-3').update(weight=0)
+        tags = [Tag.objects.get(slug='tag-1'), Tag.objects.get(slug='tag-2')]
+        for site in Site.objects.bulk_create(Site(name=f'Site {i}', slug=f'site-{i}') for i in range(4, 10)):
+            site.tags.set(tags)
+        expected = [
+            obj.pk for obj in sorted(
+                TaggedItem.objects.select_related('tag'), key=lambda obj: (obj.tag.weight, obj.tag.name, obj.pk)
+            )
+        ]
+
+        url = reverse('extras-api:taggeditem-list')
+        pks = []
+        for offset in range(0, len(expected), 5):
+            response = self.client.get(url, {'limit': 5, 'offset': offset}, **self.header)
+            self.assertHttpStatus(response, status.HTTP_200_OK)
+            pks.extend(item['id'] for item in response.data['results'])
+        self.assertEqual(pks, expected)
+        self.assertTrue(TaggedItemViewSet.queryset.totally_ordered)
+
 
 
 # TODO: Standardize to APIViewTestCase (needs create & update tests)
 # TODO: Standardize to APIViewTestCase (needs create & update tests)
 class ImageAttachmentTestCase(
 class ImageAttachmentTestCase(

+ 52 - 0
netbox/extras/tests/test_models.py

@@ -446,6 +446,29 @@ class TableConfigTestCase(TestCase):
         with self.assertRaises(ValidationError):
         with self.assertRaises(ValidationError):
             tc.full_clean()
             tc.full_clean()
 
 
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """Table configs sharing a weight and name are paginated once each, by weight, name and then primary key."""
+        # Weight order runs opposite to name order
+        TableConfig.objects.bulk_create(
+            TableConfig(
+                object_type=self.site_ct,
+                table=self.table_name,
+                name=f'Table Config {i}',
+                weight=300 - 100 * i,
+                columns=['name'],
+            )
+            for _ in range(4) for i in range(3)
+        )
+        expected = [
+            obj.pk for obj in sorted(TableConfig.objects.all(), key=lambda obj: (obj.weight, obj.name, obj.pk))
+        ]
+
+        queryset = TableConfig.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
 
 
 class TagTestCase(TestCase):
 class TagTestCase(TestCase):
 
 
@@ -1178,6 +1201,19 @@ class ConfigTemplateTestCase(TestCase):
             )
             )
             self.assertEqual(autosync_records.count(), 0, "AutoSyncRecord should be deleted after detaching")
             self.assertEqual(autosync_records.count(), 0, "AutoSyncRecord should be deleted after detaching")
 
 
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """Config templates sharing a name are paginated once each, in name and then primary key order."""
+        ConfigTemplate.objects.bulk_create(
+            ConfigTemplate(name=f'Config Template {i}', template_code='x') for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(ConfigTemplate.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = ConfigTemplate.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
 
 
 class ConfigTemplateDebugTestCase(TestCase):
 class ConfigTemplateDebugTestCase(TestCase):
     """
     """
@@ -1331,6 +1367,22 @@ class SanitizeHTTPHeaderFilterTestCase(TestCase):
             render_jinja2("{{ 'x' | header_safe }}", {})
             render_jinja2("{{ 'x' | header_safe }}", {})
 
 
 
 
+class ExportTemplateTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """Export templates sharing a name are paginated once each, in name and then primary key order."""
+        ExportTemplate.objects.bulk_create(
+            ExportTemplate(name=f'Export Template {i}', template_code='x') for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(ExportTemplate.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = ExportTemplate.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
+
 class ExportTemplateContextTestCase(TestCase):
 class ExportTemplateContextTestCase(TestCase):
     """
     """
     Tests for ExportTemplate.get_context() including public model population.
     Tests for ExportTemplate.get_context() including public model population.

+ 41 - 0
netbox/tenancy/migrations/0028_default_ordering_tiebreakers.py

@@ -0,0 +1,41 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('extras', '0146_default_ordering_tiebreakers'),
+        ('tenancy', '0027_fix_ltree_cascade_triggers'),
+        ('users', '0016_default_ordering_indexes'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='contact',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='contactgroup',
+            options={'ordering': ('sort_path', 'pk')},
+        ),
+        migrations.AlterModelOptions(
+            name='tenant',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.RemoveIndex(
+            model_name='contact',
+            name='tenancy_con_name_c26153_idx',
+        ),
+        migrations.RemoveIndex(
+            model_name='contactgroup',
+            name='tenancy_cg_sort_path_idx',
+        ),
+        migrations.AddIndex(
+            model_name='contact',
+            index=models.Index(fields=['name', 'id'], name='tenancy_con_name_4deb93_idx'),
+        ),
+        migrations.AddIndex(
+            model_name='contactgroup',
+            index=models.Index(fields=['sort_path', 'id'], name='tenancy_cg_sort_path_idx'),
+        ),
+    ]

+ 4 - 4
netbox/tenancy/models/contacts.py

@@ -47,10 +47,10 @@ class ContactGroup(NestedLtreeGroupModel):
     objects = ContactGroupManager()
     objects = ContactGroupManager()
 
 
     class Meta:
     class Meta:
-        ordering = ('sort_path',)
+        ordering = ('sort_path', 'pk')  # sort_path may be non-unique
         indexes = (
         indexes = (
             GistIndex(fields=['path'], name='tenancy_contactgroup_path_gist'),
             GistIndex(fields=['path'], name='tenancy_contactgroup_path_gist'),
-            models.Index(fields=['sort_path'], name='tenancy_cg_sort_path_idx'),
+            models.Index(fields=['sort_path', 'id'], name='tenancy_cg_sort_path_idx'),
         )
         )
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
@@ -116,9 +116,9 @@ class Contact(PrimaryModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('contact')
         verbose_name = _('contact')
         verbose_name_plural = _('contacts')
         verbose_name_plural = _('contacts')

+ 1 - 1
netbox/tenancy/models/tenants.py

@@ -84,7 +84,7 @@ class Tenant(ContactsMixin, PrimaryModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
                 fields=('group', 'name'),
                 fields=('group', 'name'),

+ 50 - 0
netbox/tenancy/tests/test_models.py

@@ -101,6 +101,27 @@ class TenantGroupTestCase(TestCase):
         self.assertIsNone(tenant.group)
         self.assertIsNone(tenant.group)
 
 
 
 
+class TenantTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Tenants sharing a name are paginated once each, in name and then primary key order.
+        """
+        groups = TenantGroup.objects.bulk_create(
+            TenantGroup(name=f'Tenant Group {i}', slug=f'tenant-group-{i}') for i in range(4)
+        )
+        Tenant.objects.bulk_create(
+            Tenant(name=f'Tenant {i}', slug=f'tenant-{i}', group=group) for group in groups for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(Tenant.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = Tenant.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
+
 class ContactGroupTestCase(TestCase):
 class ContactGroupTestCase(TestCase):
 
 
     @classmethod
     @classmethod
@@ -168,3 +189,32 @@ class ContactGroupTestCase(TestCase):
         queryset = ContactGroup.objects.annotate_contacts()
         queryset = ContactGroup.objects.annotate_contacts()
         self.assertEqual(queryset.get(pk=self.group_a.pk).contact_count, 0)
         self.assertEqual(queryset.get(pk=self.group_a.pk).contact_count, 0)
         self.assertEqual(queryset.get(pk=self.group_b.pk).contact_count, 0)
         self.assertEqual(queryset.get(pk=self.group_b.pk).contact_count, 0)
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """Root contact groups sharing a name are paginated once each, in name and then primary key order."""
+        ContactGroup.objects.bulk_create(
+            ContactGroup(name=f'Contact Group {i}', slug=f'contact-group-{n}-{i}') for n in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(ContactGroup.objects.all(), key=lambda obj: (obj.sort_path, obj.pk))]
+
+        queryset = ContactGroup.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
+
+class ContactTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Contacts sharing a name are paginated once each, in name and then primary key order.
+        """
+        Contact.objects.bulk_create(Contact(name=f'Contact {i}') for _ in range(4) for i in range(3))
+        expected = [obj.pk for obj in sorted(Contact.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = Contact.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)

+ 24 - 0
netbox/users/migrations/0017_default_ordering_tiebreakers.py

@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('contenttypes', '0002_remove_content_type_name'),
+        ('users', '0016_default_ordering_indexes'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='objectpermission',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.RemoveIndex(
+            model_name='objectpermission',
+            name='users_objec_name_ca707b_idx',
+        ),
+        migrations.AddIndex(
+            model_name='objectpermission',
+            index=models.Index(fields=['name', 'id'], name='users_objec_name_0248fc_idx'),
+        ),
+    ]

+ 2 - 2
netbox/users/models/permissions.py

@@ -54,9 +54,9 @@ class ObjectPermission(CloningMixin, models.Model):
     objects = RestrictedQuerySet.as_manager()
     objects = RestrictedQuerySet.as_manager()
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
         )
         )
         verbose_name = _('permission')
         verbose_name = _('permission')
         verbose_name_plural = _('permissions')
         verbose_name_plural = _('permissions')

+ 20 - 2
netbox/users/tests/test_models.py

@@ -3,12 +3,12 @@ from datetime import timedelta
 from unittest.mock import patch
 from unittest.mock import patch
 
 
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
-from django.test import TestCase, override_settings
+from django.test import TestCase, override_settings, tag
 from django.utils import timezone
 from django.utils import timezone
 
 
 from users.choices import TokenVersionChoices
 from users.choices import TokenVersionChoices
 from users.constants import TOKEN_CHARSET, TOKEN_DEFAULT_LENGTH
 from users.constants import TOKEN_CHARSET, TOKEN_DEFAULT_LENGTH
-from users.models import Token, User
+from users.models import ObjectPermission, Token, User
 from utilities.testing import create_test_user
 from utilities.testing import create_test_user
 
 
 
 
@@ -272,3 +272,21 @@ class RestrictedQuerySetTestCase(TestCase):
         user = User.objects.create(username='inactive_su', is_superuser=True, is_active=False)
         user = User.objects.create(username='inactive_su', is_superuser=True, is_active=False)
         self.assertNotIn(self.token, Token.objects.restrict(user, 'view'))
         self.assertNotIn(self.token, Token.objects.restrict(user, 'view'))
         self.assertEqual(Token.objects.restrict(user, 'view').count(), 0)
         self.assertEqual(Token.objects.restrict(user, 'view').count(), 0)
+
+
+class ObjectPermissionTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        """
+        Permissions sharing a name are paginated once each, in name and then primary key order.
+        """
+        ObjectPermission.objects.bulk_create(
+            ObjectPermission(name=f'Permission {i}', actions=['view']) for _ in range(4) for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(ObjectPermission.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = ObjectPermission.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)

+ 24 - 0
netbox/virtualization/migrations/0061_default_ordering_tiebreakers.py

@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('contenttypes', '0002_remove_content_type_name'),
+        ('dcim', '0252_default_ordering_tiebreakers'),
+        ('extras', '0146_default_ordering_tiebreakers'),
+        ('tenancy', '0028_default_ordering_tiebreakers'),
+        ('users', '0017_default_ordering_tiebreakers'),
+        ('virtualization', '0060_consolidate_unique_constraints'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='cluster',
+            options={'ordering': ('name', 'pk')},
+        ),
+        migrations.AddIndex(
+            model_name='cluster',
+            index=models.Index(fields=['name', 'id'], name='virtualizat_name_32a74d_idx'),
+        ),
+    ]

+ 3 - 5
netbox/virtualization/models/clusters.py

@@ -96,9 +96,10 @@ class Cluster(ContactsMixin, CachedScopeMixin, PrimaryModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ['name']
+        ordering = ('name', 'pk')  # Name may be non-unique
         indexes = (
         indexes = (
-            models.Index(fields=('name',)),  # Default ordering
+            models.Index(fields=('name', 'id')),  # Default ordering
+            models.Index(fields=('scope_type', 'scope_id')),
         )
         )
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
@@ -110,9 +111,6 @@ class Cluster(ContactsMixin, CachedScopeMixin, PrimaryModel):
                 name='%(app_label)s_%(class)s_unique__site_name'
                 name='%(app_label)s_%(class)s_unique__site_name'
             ),
             ),
         )
         )
-        indexes = (
-            models.Index(fields=('scope_type', 'scope_id')),
-        )
         verbose_name = _('cluster')
         verbose_name = _('cluster')
         verbose_name_plural = _('clusters')
         verbose_name_plural = _('clusters')
 
 

+ 15 - 0
netbox/virtualization/tests/test_models.py

@@ -61,6 +61,21 @@ class ClusterTestCase(TestCase):
 
 
         self.assertFalse(Cluster.objects.filter(pk=cluster.pk).exists())
         self.assertFalse(Cluster.objects.filter(pk=cluster.pk).exists())
 
 
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_name_pagination(self):
+        groups = ClusterGroup.objects.bulk_create(
+            ClusterGroup(name=f'Cluster Group {i}', slug=f'cluster-group-{i}') for i in range(4)
+        )
+        Cluster.objects.bulk_create(
+            Cluster(name=f'Cluster {i}', type=self.cluster_type, group=group) for group in groups for i in range(3)
+        )
+        expected = [obj.pk for obj in sorted(Cluster.objects.all(), key=lambda obj: (obj.name, obj.pk))]
+
+        queryset = Cluster.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)
+
 
 
 class VirtualMachineTypeTestCase(TestCase):
 class VirtualMachineTypeTestCase(TestCase):
 
 

+ 15 - 0
netbox/vpn/migrations/0014_default_ordering_tiebreakers.py

@@ -0,0 +1,15 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('vpn', '0013_consolidate_unique_constraints'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='l2vpntermination',
+            options={'ordering': ('l2vpn', 'pk')},
+        ),
+    ]

+ 1 - 1
netbox/vpn/models/l2vpn.py

@@ -106,7 +106,7 @@ class L2VPNTermination(NetBoxModel):
     )
     )
 
 
     class Meta:
     class Meta:
-        ordering = ('l2vpn',)
+        ordering = ('l2vpn', 'pk')
         constraints = (
         constraints = (
             models.UniqueConstraint(
             models.UniqueConstraint(
                 fields=('assigned_object_type', 'assigned_object_id'),
                 fields=('assigned_object_type', 'assigned_object_id'),

+ 23 - 1
netbox/vpn/tests/test_models.py

@@ -1,8 +1,9 @@
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
-from django.test import TestCase
+from django.test import TestCase, tag
 
 
 from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site
 from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site
 from ipam.models import VLAN
 from ipam.models import VLAN
+from vpn.choices import L2VPNTypeChoices
 from vpn.models import *
 from vpn.models import *
 
 
 
 
@@ -77,3 +78,24 @@ class L2VPNTerminationTestCase(TestCase):
         L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=vlan)
         L2VPNTermination.objects.create(l2vpn=l2vpn, assigned_object=vlan)
         duplicate = L2VPNTermination(l2vpn=l2vpn, assigned_object=vlan)
         duplicate = L2VPNTermination(l2vpn=l2vpn, assigned_object=vlan)
         self.assertRaises(ValidationError, duplicate.clean)
         self.assertRaises(ValidationError, duplicate.clean)
+
+    @tag('regression')  # Ref: #23818
+    def test_duplicate_l2vpn_pagination(self):
+        # Sorts first by name but last by primary key
+        L2VPN.objects.create(name='L2VPN 0', slug='l2vpn-0', type=L2VPNTypeChoices.TYPE_VPLS)
+        # Point-to-point L2VPNs accept only two terminations
+        l2vpns = list(L2VPN.objects.exclude(type__in=L2VPNTypeChoices.P2P))
+        vlans = VLAN.objects.bulk_create(VLAN(name=f'VLAN {vid}', vid=vid) for vid in range(700, 712))
+        L2VPNTermination.objects.bulk_create(
+            L2VPNTermination(l2vpn=l2vpns[i % len(l2vpns)], assigned_object=vlan) for i, vlan in enumerate(vlans)
+        )
+        expected = [
+            obj.pk for obj in sorted(
+                L2VPNTermination.objects.select_related('l2vpn'), key=lambda obj: (obj.l2vpn.name, obj.pk)
+            )
+        ]
+
+        queryset = L2VPNTermination.objects.values_list('pk', flat=True)
+        paginated = [pk for offset in range(0, len(expected), 5) for pk in queryset[offset:offset + 5]]
+        self.assertEqual(paginated, expected)
+        self.assertTrue(queryset.totally_ordered)