prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Inconsistent /api/virtualization/interfaces/ results
  <!--
      Before opening a new issue, please search through the existing issues to
      see if your topic has already been addressed. Note that you may need to
      remove the "is:open" filter from the search bar to include closed issues.
  
      Check the appropriate type for your issue below by placing an x between the
      brackets. For assistance with installation issues, or for any other issues
      other than those listed below, please raise your topic for discussion on
      our mailing list:
  
          https://groups.google.com/forum/#!forum/netbox-discuss
  
      Please note that issues which do not fall under any of the below categories
      will be closed. Due to an excessive backlog of feature requests, we are
      not currently accepting any proposals which extend NetBox's feature scope.
  
      Do not prepend any sort of tag to your issue's title. An administrator will
      review your issue and assign labels as appropriate.
  --->
  ### Issue type
  [ ] Feature request <!-- An enhancement of existing functionality -->
  [ x  ] Bug report      <!-- Unexpected or erroneous behavior -->
  [ ] Documentation   <!-- A modification to the documentation -->
  
  <!--
      Please describe the environment in which you are running NetBox. (Be sure
      to verify that you are running the latest stable release of NetBox before
      submitting a bug report.) If you are submitting a bug report and have made
      any changes to the code base, please first validate that your bug can be
      recreated while running an official release.
  -->
  ### Environment
  * Python version:  3.6.5
  * NetBox version:  2.3.4
  
  <!--
      BUG REPORTS must include:
          * A list of the steps needed for someone else to reproduce the bug
          * A description of the expected and observed behavior
          * Any relevant error messages (screenshots may also help)
  
      FEATURE REQUESTS must include:
          * A detailed description of the proposed functionality
          * A use case for the new feature
          * A rough description of any necessary changes to the database schema
          * Any relevant third-party libraries which would be needed
  -->
  ### Description
  
  Querying all virtualized interfaces returns inconsistents results : the count is OK, but some interfaces are missing and some are duplicated.
  
  The underlying query is ordering by an empty column ("dcim_device"."name") which seems to fall under the non predictable results case : https://www.postgresql.org/docs/current/static/queries-limit.html
  
  ```sql
  ... WHERE "dcim_interface"."virtual_machine_id" IS NOT NULL 
  ORDER BY "dcim_device"."name" ASC, "dcim_interface"."name" ASC LIMIT 1000 OFFSET 50
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `netbox/dcim/managers.py`
  Content:
  ```
  1 from django.db.models import Manager, QuerySet
  2 from django.db.models.expressions import RawSQL
  3 
  4 from .constants import NONCONNECTABLE_IFACE_TYPES
  5 
  6 # Regular expressions for parsing Interface names
  7 TYPE_RE = r"SUBSTRING({} FROM '^([^0-9\.:]+)')"
  8 SLOT_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(\d{{1,9}})/') AS integer), NULL)"
  9 SUBSLOT_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9\.:]+)?\d{{1,9}}/(\d{{1,9}})') AS integer), NULL)"
  10 POSITION_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\d{{1,9}}/){{2}}(\d{{1,9}})') AS integer), NULL)"
  11 SUBPOSITION_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\d{{1,9}}/){{3}}(\d{{1,9}})') AS integer), NULL)"
  12 ID_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9\.:]+)?(\d{{1,9}})([^/]|$)') AS integer)"
  13 CHANNEL_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^.*:(\d{{1,9}})(\.\d{{1,9}})?$') AS integer), 0)"
  14 VC_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^.*\.(\d{{1,9}})$') AS integer), 0)"
  15 
  16 
  17 class DeviceComponentManager(Manager):
  18 
  19     def get_queryset(self):
  20 
  21         queryset = super().get_queryset()
  22         table_name = self.model._meta.db_table
  23         sql = r"CONCAT(REGEXP_REPLACE({}.name, '\d+$', ''), LPAD(SUBSTRING({}.name FROM '\d+$'), 8, '0'))"
  24 
  25         # Pad any trailing digits to effect natural sorting
  26         return queryset.extra(
  27             select={
  28                 'name_padded': sql.format(table_name, table_name),
  29             }
  30         ).order_by('name_padded', 'pk')
  31 
  32 
  33 class InterfaceQuerySet(QuerySet):
  34 
  35     def connectable(self):
  36         """
  37         Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or
  38         wireless).
  39         """
  40         return self.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES)
  41 
  42 
  43 class InterfaceManager(Manager):
  44 
  45     def get_queryset(self):
  46         """
  47         Naturally order interfaces by their type and numeric position. To order interfaces naturally, the `name` field
  48         is split into eight distinct components: leading text (type), slot, subslot, position, subposition, ID, channel,
  49         and virtual circuit:
  50 
  51             {type}{slot or ID}/{subslot}/{position}/{subposition}:{channel}.{vc}
  52 
  53         Components absent from the interface name are coalesced to zero or null. For example, an interface named
  54         GigabitEthernet1/2/3 would be parsed as follows:
  55 
  56             type = 'GigabitEthernet'
  57             slot =  1
  58             subslot = 2
  59             position = 3
  60             subposition = None
  61             id = None
  62             channel = 0
  63             vc = 0
  64 
  65         The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not
  66         match any of the prescribed fields.
  67         """
  68 
  69         sql_col = '{}.name'.format(self.model._meta.db_table)
  70         ordering = [
  71             '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name',
  72         ]
  73 
  74         fields = {
  75             '_type': RawSQL(TYPE_RE.format(sql_col), []),
  76             '_id': RawSQL(ID_RE.format(sql_col), []),
  77             '_slot': RawSQL(SLOT_RE.format(sql_col), []),
  78             '_subslot': RawSQL(SUBSLOT_RE.format(sql_col), []),
  79             '_position': RawSQL(POSITION_RE.format(sql_col), []),
  80             '_subposition': RawSQL(SUBPOSITION_RE.format(sql_col), []),
  81             '_channel': RawSQL(CHANNEL_RE.format(sql_col), []),
  82             '_vc': RawSQL(VC_RE.format(sql_col), []),
  83         }
  84 
  85         return InterfaceQuerySet(self.model, using=self._db).annotate(**fields).order_by(*ordering)
  86
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/netbox/dcim/managers.py b/netbox/dcim/managers.py
  --- a/netbox/dcim/managers.py
  +++ b/netbox/dcim/managers.py
  @@ -64,11 +64,15 @@
   
           The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not
           match any of the prescribed fields.
  +
  +        The `id` field is included to enforce deterministic ordering of interfaces in similar vein of other device
  +        components.
           """
   
           sql_col = '{}.name'.format(self.model._meta.db_table)
           ordering = [
  -            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name',
  +            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name', 'pk'
  +
           ]
   
           fields = {
  
verification_info: {"golden_diff": "diff --git a/netbox/dcim/managers.py b/netbox/dcim/managers.py\n--- a/netbox/dcim/managers.py\n+++ b/netbox/dcim/managers.py\n@@ -64,11 +64,15 @@\n \n         The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not\n         match any of the prescribed fields.\n+\n+        The `id` field is included to enforce deterministic ordering of interfaces in similar vein of other device\n+        components.\n         \"\"\"\n \n         sql_col = '{}.name'.format(self.model._meta.db_table)\n         ordering = [\n-            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name',\n+            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name', 'pk'\n+\n         ]\n \n         fields = {\n", "issue": "Inconsistent /api/virtualization/interfaces/ results\n<!--\r\n    Before opening a new issue, please search through the existing issues to\r\n    see if your topic has already been addressed. Note that you may need to\r\n    remove the \"is:open\" filter from the search bar to include closed issues.\r\n\r\n    Check the appropriate type for your issue below by placing an x between the\r\n    brackets. For assistance with installation issues, or for any other issues\r\n    other than those listed below, please raise your topic for discussion on\r\n    our mailing list:\r\n\r\n        https://groups.google.com/forum/#!forum/netbox-discuss\r\n\r\n    Please note that issues which do not fall under any of the below categories\r\n    will be closed. Due to an excessive backlog of feature requests, we are\r\n    not currently accepting any proposals which extend NetBox's feature scope.\r\n\r\n    Do not prepend any sort of tag to your issue's title. An administrator will\r\n    review your issue and assign labels as appropriate.\r\n--->\r\n### Issue type\r\n[ ] Feature request <!-- An enhancement of existing functionality -->\r\n[ x  ] Bug report      <!-- Unexpected or erroneous behavior -->\r\n[ ] Documentation   <!-- A modification to the documentation -->\r\n\r\n<!--\r\n    Please describe the environment in which you are running NetBox. (Be sure\r\n    to verify that you are running the latest stable release of NetBox before\r\n    submitting a bug report.) If you are submitting a bug report and have made\r\n    any changes to the code base, please first validate that your bug can be\r\n    recreated while running an official release.\r\n-->\r\n### Environment\r\n* Python version:  3.6.5\r\n* NetBox version:  2.3.4\r\n\r\n<!--\r\n    BUG REPORTS must include:\r\n        * A list of the steps needed for someone else to reproduce the bug\r\n        * A description of the expected and observed behavior\r\n        * Any relevant error messages (screenshots may also help)\r\n\r\n    FEATURE REQUESTS must include:\r\n        * A detailed description of the proposed functionality\r\n        * A use case for the new feature\r\n        * A rough description of any necessary changes to the database schema\r\n        * Any relevant third-party libraries which would be needed\r\n-->\r\n### Description\r\n\r\nQuerying all virtualized interfaces returns inconsistents results : the count is OK, but some interfaces are missing and some are duplicated.\r\n\r\nThe underlying query is ordering by an empty column (\"dcim_device\".\"name\") which seems to fall under the non predictable results case : https://www.postgresql.org/docs/current/static/queries-limit.html\r\n\r\n```sql\r\n... WHERE \"dcim_interface\".\"virtual_machine_id\" IS NOT NULL \r\nORDER BY \"dcim_device\".\"name\" ASC, \"dcim_interface\".\"name\" ASC LIMIT 1000 OFFSET 50\r\n```\n", "before_files": [{"content": "from django.db.models import Manager, QuerySet\nfrom django.db.models.expressions import RawSQL\n\nfrom .constants import NONCONNECTABLE_IFACE_TYPES\n\n# Regular expressions for parsing Interface names\nTYPE_RE = r\"SUBSTRING({} FROM '^([^0-9\\.:]+)')\"\nSLOT_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(\\d{{1,9}})/') AS integer), NULL)\"\nSUBSLOT_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9\\.:]+)?\\d{{1,9}}/(\\d{{1,9}})') AS integer), NULL)\"\nPOSITION_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\\d{{1,9}}/){{2}}(\\d{{1,9}})') AS integer), NULL)\"\nSUBPOSITION_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\\d{{1,9}}/){{3}}(\\d{{1,9}})') AS integer), NULL)\"\nID_RE = r\"CAST(SUBSTRING({} FROM '^(?:[^0-9\\.:]+)?(\\d{{1,9}})([^/]|$)') AS integer)\"\nCHANNEL_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^.*:(\\d{{1,9}})(\\.\\d{{1,9}})?$') AS integer), 0)\"\nVC_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^.*\\.(\\d{{1,9}})$') AS integer), 0)\"\n\n\nclass DeviceComponentManager(Manager):\n\n    def get_queryset(self):\n\n        queryset = super().get_queryset()\n        table_name = self.model._meta.db_table\n        sql = r\"CONCAT(REGEXP_REPLACE({}.name, '\\d+$', ''), LPAD(SUBSTRING({}.name FROM '\\d+$'), 8, '0'))\"\n\n        # Pad any trailing digits to effect natural sorting\n        return queryset.extra(\n            select={\n                'name_padded': sql.format(table_name, table_name),\n            }\n        ).order_by('name_padded', 'pk')\n\n\nclass InterfaceQuerySet(QuerySet):\n\n    def connectable(self):\n        \"\"\"\n        Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or\n        wireless).\n        \"\"\"\n        return self.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES)\n\n\nclass InterfaceManager(Manager):\n\n    def get_queryset(self):\n        \"\"\"\n        Naturally order interfaces by their type and numeric position. To order interfaces naturally, the `name` field\n        is split into eight distinct components: leading text (type), slot, subslot, position, subposition, ID, channel,\n        and virtual circuit:\n\n            {type}{slot or ID}/{subslot}/{position}/{subposition}:{channel}.{vc}\n\n        Components absent from the interface name are coalesced to zero or null. For example, an interface named\n        GigabitEthernet1/2/3 would be parsed as follows:\n\n            type = 'GigabitEthernet'\n            slot =  1\n            subslot = 2\n            position = 3\n            subposition = None\n            id = None\n            channel = 0\n            vc = 0\n\n        The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not\n        match any of the prescribed fields.\n        \"\"\"\n\n        sql_col = '{}.name'.format(self.model._meta.db_table)\n        ordering = [\n            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name',\n        ]\n\n        fields = {\n            '_type': RawSQL(TYPE_RE.format(sql_col), []),\n            '_id': RawSQL(ID_RE.format(sql_col), []),\n            '_slot': RawSQL(SLOT_RE.format(sql_col), []),\n            '_subslot': RawSQL(SUBSLOT_RE.format(sql_col), []),\n            '_position': RawSQL(POSITION_RE.format(sql_col), []),\n            '_subposition': RawSQL(SUBPOSITION_RE.format(sql_col), []),\n            '_channel': RawSQL(CHANNEL_RE.format(sql_col), []),\n            '_vc': RawSQL(VC_RE.format(sql_col), []),\n        }\n\n        return InterfaceQuerySet(self.model, using=self._db).annotate(**fields).order_by(*ordering)\n", "path": "netbox/dcim/managers.py"}], "after_files": [{"content": "from django.db.models import Manager, QuerySet\nfrom django.db.models.expressions import RawSQL\n\nfrom .constants import NONCONNECTABLE_IFACE_TYPES\n\n# Regular expressions for parsing Interface names\nTYPE_RE = r\"SUBSTRING({} FROM '^([^0-9\\.:]+)')\"\nSLOT_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(\\d{{1,9}})/') AS integer), NULL)\"\nSUBSLOT_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9\\.:]+)?\\d{{1,9}}/(\\d{{1,9}})') AS integer), NULL)\"\nPOSITION_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\\d{{1,9}}/){{2}}(\\d{{1,9}})') AS integer), NULL)\"\nSUBPOSITION_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\\d{{1,9}}/){{3}}(\\d{{1,9}})') AS integer), NULL)\"\nID_RE = r\"CAST(SUBSTRING({} FROM '^(?:[^0-9\\.:]+)?(\\d{{1,9}})([^/]|$)') AS integer)\"\nCHANNEL_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^.*:(\\d{{1,9}})(\\.\\d{{1,9}})?$') AS integer), 0)\"\nVC_RE = r\"COALESCE(CAST(SUBSTRING({} FROM '^.*\\.(\\d{{1,9}})$') AS integer), 0)\"\n\n\nclass DeviceComponentManager(Manager):\n\n    def get_queryset(self):\n\n        queryset = super().get_queryset()\n        table_name = self.model._meta.db_table\n        sql = r\"CONCAT(REGEXP_REPLACE({}.name, '\\d+$', ''), LPAD(SUBSTRING({}.name FROM '\\d+$'), 8, '0'))\"\n\n        # Pad any trailing digits to effect natural sorting\n        return queryset.extra(\n            select={\n                'name_padded': sql.format(table_name, table_name),\n            }\n        ).order_by('name_padded', 'pk')\n\n\nclass InterfaceQuerySet(QuerySet):\n\n    def connectable(self):\n        \"\"\"\n        Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or\n        wireless).\n        \"\"\"\n        return self.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES)\n\n\nclass InterfaceManager(Manager):\n\n    def get_queryset(self):\n        \"\"\"\n        Naturally order interfaces by their type and numeric position. To order interfaces naturally, the `name` field\n        is split into eight distinct components: leading text (type), slot, subslot, position, subposition, ID, channel,\n        and virtual circuit:\n\n            {type}{slot or ID}/{subslot}/{position}/{subposition}:{channel}.{vc}\n\n        Components absent from the interface name are coalesced to zero or null. For example, an interface named\n        GigabitEthernet1/2/3 would be parsed as follows:\n\n            type = 'GigabitEthernet'\n            slot =  1\n            subslot = 2\n            position = 3\n            subposition = None\n            id = None\n            channel = 0\n            vc = 0\n\n        The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not\n        match any of the prescribed fields.\n\n        The `id` field is included to enforce deterministic ordering of interfaces in similar vein of other device\n        components.\n        \"\"\"\n\n        sql_col = '{}.name'.format(self.model._meta.db_table)\n        ordering = [\n            '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name', 'pk'\n\n        ]\n\n        fields = {\n            '_type': RawSQL(TYPE_RE.format(sql_col), []),\n            '_id': RawSQL(ID_RE.format(sql_col), []),\n            '_slot': RawSQL(SLOT_RE.format(sql_col), []),\n            '_subslot': RawSQL(SUBSLOT_RE.format(sql_col), []),\n            '_position': RawSQL(POSITION_RE.format(sql_col), []),\n            '_subposition': RawSQL(SUBPOSITION_RE.format(sql_col), []),\n            '_channel': RawSQL(CHANNEL_RE.format(sql_col), []),\n            '_vc': RawSQL(VC_RE.format(sql_col), []),\n        }\n\n        return InterfaceQuerySet(self.model, using=self._db).annotate(**fields).order_by(*ordering)\n", "path": "netbox/dcim/managers.py"}]}