We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Showing config context with multiple tags assigned fails with MultipleObjectsReturned
### Environment
* Python version: 3.8.6
* NetBox version: 2.9.10

### Steps to Reproduce
1. create a virtual machine
2. add two tags (which result in adding data to config context)
3. Open Config context of that VM

<!-- What did you expect to happen? -->
### Expected Behavior
See config context

<!-- What happened instead? -->
### Observed Behavior
See an error
```
<class 'virtualization.models.VirtualMachine.MultipleObjectsReturned'>

get() returned more than one VirtualMachine -- it returned 2!
```
```
netbox_1         | Internal Server Error: /virtualization/virtual-machines/70/config-context/
netbox_1         | Traceback (most recent call last):
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
netbox_1         |     response = get_response(request)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
netbox_1         |     response = wrapped_callback(request, *callback_args, **callback_kwargs)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 73, in view
netbox_1         |     return self.dispatch(request, *args, **kwargs)
netbox_1         |   File "/opt/netbox/netbox/utilities/views.py", line 124, in dispatch
netbox_1         |     return super().dispatch(request, *args, **kwargs)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 101, in dispatch
netbox_1         |     return handler(request, *args, **kwargs)
netbox_1         |   File "/opt/netbox/netbox/extras/views.py", line 146, in get
netbox_1         |     obj = get_object_or_404(self.queryset, pk=pk)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/shortcuts.py", line 76, in get_object_or_404
netbox_1         |     return queryset.get(*args, **kwargs)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/cacheops/query.py", line 353, in get
netbox_1         |     return qs._no_monkey.get(qs, *args, **kwargs)
netbox_1         |   File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 433, in get
netbox_1         |     raise self.model.MultipleObjectsReturned(
netbox_1         | virtualization.models.VirtualMachine.MultipleObjectsReturned: get() returned more than one VirtualMachine -- it returned 2!
netbox_1         | 192.168.80.7 - - [29/Nov/2020:18:45:03 +0000] "GET /virtualization/virtual-machines/70/config-context/ HTTP/1.0" 500 1855 "-" "<cut>"
```

Note: I wrote this already in https://github.com/netbox-community/netbox/issues/5314#issuecomment-724722310 and [a change](https://github.com/netbox-community/netbox/commit/0d27abc6fc22a8d40183a59eceef5dda57e99eae) got introduced for 2.9 to fix it but in 2.10 it is still present.
I got asked to create a new issue.

--- 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/extras/querysets.py`
Content:
```
1 from collections import OrderedDict
2 
3 from django.db.models import OuterRef, Subquery, Q
4 
5 from utilities.query_functions import EmptyGroupByJSONBAgg, OrderableJSONBAgg
6 from utilities.querysets import RestrictedQuerySet
7 
8 
9 class CustomFieldQueryset:
10     """
11     Annotate custom fields on objects within a QuerySet.
12     """
13     def __init__(self, queryset, custom_fields):
14         self.queryset = queryset
15         self.model = queryset.model
16         self.custom_fields = custom_fields
17 
18     def __iter__(self):
19         for obj in self.queryset:
20             values_dict = {cfv.field_id: cfv.value for cfv in obj.custom_field_values.all()}
21             obj.custom_fields = OrderedDict([(field, values_dict.get(field.pk)) for field in self.custom_fields])
22             yield obj
23 
24 
25 class ConfigContextQuerySet(RestrictedQuerySet):
26 
27     def get_for_object(self, obj, aggregate_data=False):
28         """
29         Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.
30 
31         Args:
32           aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects
33         """
34 
35         # `device_role` for Device; `role` for VirtualMachine
36         role = getattr(obj, 'device_role', None) or obj.role
37 
38         # Virtualization cluster for VirtualMachine
39         cluster = getattr(obj, 'cluster', None)
40         cluster_group = getattr(cluster, 'group', None)
41 
42         # Get the group of the assigned tenant, if any
43         tenant_group = obj.tenant.group if obj.tenant else None
44 
45         # Match against the directly assigned region as well as any parent regions.
46         region = getattr(obj.site, 'region', None)
47         if region:
48             regions = region.get_ancestors(include_self=True)
49         else:
50             regions = []
51 
52         queryset = self.filter(
53             Q(regions__in=regions) | Q(regions=None),
54             Q(sites=obj.site) | Q(sites=None),
55             Q(roles=role) | Q(roles=None),
56             Q(platforms=obj.platform) | Q(platforms=None),
57             Q(cluster_groups=cluster_group) | Q(cluster_groups=None),
58             Q(clusters=cluster) | Q(clusters=None),
59             Q(tenant_groups=tenant_group) | Q(tenant_groups=None),
60             Q(tenants=obj.tenant) | Q(tenants=None),
61             Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),
62             is_active=True,
63         ).order_by('weight', 'name').distinct()
64 
65         if aggregate_data:
66             return queryset.aggregate(
67                 config_context_data=OrderableJSONBAgg('data', ordering=['weight', 'name'])
68             )['config_context_data']
69 
70         return queryset
71 
72 
73 class ConfigContextModelQuerySet(RestrictedQuerySet):
74     """
75     QuerySet manager used by models which support ConfigContext (device and virtual machine).
76 
77     Includes a method which appends an annotation of aggregated config context JSON data objects. This is
78     implemented as a subquery which performs all the joins necessary to filter relevant config context objects.
79     This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with
80     multiple objects.
81 
82     This allows the annotation to be entirely optional.
83     """
84 
85     def annotate_config_context_data(self):
86         """
87         Attach the subquery annotation to the base queryset
88         """
89         from extras.models import ConfigContext
90         return self.annotate(
91             config_context_data=Subquery(
92                 ConfigContext.objects.filter(
93                     self._get_config_context_filters()
94                 ).annotate(
95                     _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])
96                 ).values("_data")
97             )
98         ).distinct()
99 
100     def _get_config_context_filters(self):
101         # Construct the set of Q objects for the specific object types
102         base_query = Q(
103             Q(platforms=OuterRef('platform')) | Q(platforms=None),
104             Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
105             Q(tenants=OuterRef('tenant')) | Q(tenants=None),
106             Q(tags=OuterRef('tags')) | Q(tags=None),
107             is_active=True,
108         )
109 
110         if self.model._meta.model_name == 'device':
111             base_query.add((Q(roles=OuterRef('device_role')) | Q(roles=None)), Q.AND)
112             base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)
113             region_field = 'site__region'
114 
115         elif self.model._meta.model_name == 'virtualmachine':
116             base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)
117             base_query.add((Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None)), Q.AND)
118             base_query.add((Q(clusters=OuterRef('cluster')) | Q(clusters=None)), Q.AND)
119             base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)
120             region_field = 'cluster__site__region'
121 
122         base_query.add(
123             (Q(
124                 regions__tree_id=OuterRef(f'{region_field}__tree_id'),
125                 regions__level__lte=OuterRef(f'{region_field}__level'),
126                 regions__lft__lte=OuterRef(f'{region_field}__lft'),
127                 regions__rght__gte=OuterRef(f'{region_field}__rght'),
128             ) | Q(regions=None)),
129             Q.AND
130         )
131 
132         return base_query
133
```
--- 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()

```

diff --git a/netbox/extras/querysets.py b/netbox/extras/querysets.py
--- a/netbox/extras/querysets.py
+++ b/netbox/extras/querysets.py
@@ -2,6 +2,7 @@
 
 from django.db.models import OuterRef, Subquery, Q
 
+from extras.models.tags import TaggedItem
 from utilities.query_functions import EmptyGroupByJSONBAgg, OrderableJSONBAgg
 from utilities.querysets import RestrictedQuerySet
 
@@ -99,11 +100,25 @@
 
     def _get_config_context_filters(self):
         # Construct the set of Q objects for the specific object types
+        tag_query_filters = {
+            "object_id": OuterRef(OuterRef('pk')),
+            "content_type__app_label": self.model._meta.app_label,
+            "content_type__model": self.model._meta.model_name
+        }
         base_query = Q(
             Q(platforms=OuterRef('platform')) | Q(platforms=None),
             Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),
             Q(tenants=OuterRef('tenant')) | Q(tenants=None),
-            Q(tags=OuterRef('tags')) | Q(tags=None),
+            Q(
+                tags__pk__in=Subquery(
+                    TaggedItem.objects.filter(
+                        **tag_query_filters
+                    ).values_list(
+                        'tag_id',
+                        flat=True
+                    )
+                )
+            ) | Q(tags=None),
             is_active=True,
         )

{"golden_diff": "diff --git a/netbox/extras/querysets.py b/netbox/extras/querysets.py\n--- a/netbox/extras/querysets.py\n+++ b/netbox/extras/querysets.py\n@@ -2,6 +2,7 @@\n \n from django.db.models import OuterRef, Subquery, Q\n \n+from extras.models.tags import TaggedItem\n from utilities.query_functions import EmptyGroupByJSONBAgg, OrderableJSONBAgg\n from utilities.querysets import RestrictedQuerySet\n \n@@ -99,11 +100,25 @@\n \n     def _get_config_context_filters(self):\n         # Construct the set of Q objects for the specific object types\n+        tag_query_filters = {\n+            \"object_id\": OuterRef(OuterRef('pk')),\n+            \"content_type__app_label\": self.model._meta.app_label,\n+            \"content_type__model\": self.model._meta.model_name\n+        }\n         base_query = Q(\n             Q(platforms=OuterRef('platform')) | Q(platforms=None),\n             Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),\n             Q(tenants=OuterRef('tenant')) | Q(tenants=None),\n-            Q(tags=OuterRef('tags')) | Q(tags=None),\n+            Q(\n+                tags__pk__in=Subquery(\n+                    TaggedItem.objects.filter(\n+                        **tag_query_filters\n+                    ).values_list(\n+                        'tag_id',\n+                        flat=True\n+                    )\n+                )\n+            ) | Q(tags=None),\n             is_active=True,\n         )\n", "issue": "Showing config context with multiple tags assigned fails with MultipleObjectsReturned\n### Environment\r\n* Python version: 3.8.6\r\n* NetBox version: 2.9.10\r\n\r\n### Steps to Reproduce\r\n1. create a virtual machine\r\n2. add two tags (which result in adding data to config context)\r\n3. Open Config context of that VM\r\n\r\n<!-- What did you expect to happen? -->\r\n### Expected Behavior\r\nSee config context\r\n\r\n<!-- What happened instead? -->\r\n### Observed Behavior\r\nSee an error\r\n```\r\n<class 'virtualization.models.VirtualMachine.MultipleObjectsReturned'>\r\n\r\nget() returned more than one VirtualMachine -- it returned 2!\r\n```\r\n```\r\nnetbox_1         | Internal Server Error: /virtualization/virtual-machines/70/config-context/\r\nnetbox_1         | Traceback (most recent call last):\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py\", line 47, in inner\r\nnetbox_1         |     response = get_response(request)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py\", line 179, in _get_response\r\nnetbox_1         |     response = wrapped_callback(request, *callback_args, **callback_kwargs)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/views/generic/base.py\", line 73, in view\r\nnetbox_1         |     return self.dispatch(request, *args, **kwargs)\r\nnetbox_1         |   File \"/opt/netbox/netbox/utilities/views.py\", line 124, in dispatch\r\nnetbox_1         |     return super().dispatch(request, *args, **kwargs)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/views/generic/base.py\", line 101, in dispatch\r\nnetbox_1         |     return handler(request, *args, **kwargs)\r\nnetbox_1         |   File \"/opt/netbox/netbox/extras/views.py\", line 146, in get\r\nnetbox_1         |     obj = get_object_or_404(self.queryset, pk=pk)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/shortcuts.py\", line 76, in get_object_or_404\r\nnetbox_1         |     return queryset.get(*args, **kwargs)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/cacheops/query.py\", line 353, in get\r\nnetbox_1         |     return qs._no_monkey.get(qs, *args, **kwargs)\r\nnetbox_1         |   File \"/usr/local/lib/python3.8/site-packages/django/db/models/query.py\", line 433, in get\r\nnetbox_1         |     raise self.model.MultipleObjectsReturned(\r\nnetbox_1         | virtualization.models.VirtualMachine.MultipleObjectsReturned: get() returned more than one VirtualMachine -- it returned 2!\r\nnetbox_1         | 192.168.80.7 - - [29/Nov/2020:18:45:03 +0000] \"GET /virtualization/virtual-machines/70/config-context/ HTTP/1.0\" 500 1855 \"-\" \"<cut>\"\r\n```\r\n\r\nNote: I wrote this already in https://github.com/netbox-community/netbox/issues/5314#issuecomment-724722310 and [a change](https://github.com/netbox-community/netbox/commit/0d27abc6fc22a8d40183a59eceef5dda57e99eae) got introduced for 2.9 to fix it but in 2.10 it is still present.\r\nI got asked to create a new issue.\n", "before_files": [{"content": "from collections import OrderedDict\n\nfrom django.db.models import OuterRef, Subquery, Q\n\nfrom utilities.query_functions import EmptyGroupByJSONBAgg, OrderableJSONBAgg\nfrom utilities.querysets import RestrictedQuerySet\n\n\nclass CustomFieldQueryset:\n    \"\"\"\n    Annotate custom fields on objects within a QuerySet.\n    \"\"\"\n    def __init__(self, queryset, custom_fields):\n        self.queryset = queryset\n        self.model = queryset.model\n        self.custom_fields = custom_fields\n\n    def __iter__(self):\n        for obj in self.queryset:\n            values_dict = {cfv.field_id: cfv.value for cfv in obj.custom_field_values.all()}\n            obj.custom_fields = OrderedDict([(field, values_dict.get(field.pk)) for field in self.custom_fields])\n            yield obj\n\n\nclass ConfigContextQuerySet(RestrictedQuerySet):\n\n    def get_for_object(self, obj, aggregate_data=False):\n        \"\"\"\n        Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.\n\n        Args:\n          aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects\n        \"\"\"\n\n        # `device_role` for Device; `role` for VirtualMachine\n        role = getattr(obj, 'device_role', None) or obj.role\n\n        # Virtualization cluster for VirtualMachine\n        cluster = getattr(obj, 'cluster', None)\n        cluster_group = getattr(cluster, 'group', None)\n\n        # Get the group of the assigned tenant, if any\n        tenant_group = obj.tenant.group if obj.tenant else None\n\n        # Match against the directly assigned region as well as any parent regions.\n        region = getattr(obj.site, 'region', None)\n        if region:\n            regions = region.get_ancestors(include_self=True)\n        else:\n            regions = []\n\n        queryset = self.filter(\n            Q(regions__in=regions) | Q(regions=None),\n            Q(sites=obj.site) | Q(sites=None),\n            Q(roles=role) | Q(roles=None),\n            Q(platforms=obj.platform) | Q(platforms=None),\n            Q(cluster_groups=cluster_group) | Q(cluster_groups=None),\n            Q(clusters=cluster) | Q(clusters=None),\n            Q(tenant_groups=tenant_group) | Q(tenant_groups=None),\n            Q(tenants=obj.tenant) | Q(tenants=None),\n            Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),\n            is_active=True,\n        ).order_by('weight', 'name').distinct()\n\n        if aggregate_data:\n            return queryset.aggregate(\n                config_context_data=OrderableJSONBAgg('data', ordering=['weight', 'name'])\n            )['config_context_data']\n\n        return queryset\n\n\nclass ConfigContextModelQuerySet(RestrictedQuerySet):\n    \"\"\"\n    QuerySet manager used by models which support ConfigContext (device and virtual machine).\n\n    Includes a method which appends an annotation of aggregated config context JSON data objects. This is\n    implemented as a subquery which performs all the joins necessary to filter relevant config context objects.\n    This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with\n    multiple objects.\n\n    This allows the annotation to be entirely optional.\n    \"\"\"\n\n    def annotate_config_context_data(self):\n        \"\"\"\n        Attach the subquery annotation to the base queryset\n        \"\"\"\n        from extras.models import ConfigContext\n        return self.annotate(\n            config_context_data=Subquery(\n                ConfigContext.objects.filter(\n                    self._get_config_context_filters()\n                ).annotate(\n                    _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])\n                ).values(\"_data\")\n            )\n        ).distinct()\n\n    def _get_config_context_filters(self):\n        # Construct the set of Q objects for the specific object types\n        base_query = Q(\n            Q(platforms=OuterRef('platform')) | Q(platforms=None),\n            Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),\n            Q(tenants=OuterRef('tenant')) | Q(tenants=None),\n            Q(tags=OuterRef('tags')) | Q(tags=None),\n            is_active=True,\n        )\n\n        if self.model._meta.model_name == 'device':\n            base_query.add((Q(roles=OuterRef('device_role')) | Q(roles=None)), Q.AND)\n            base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)\n            region_field = 'site__region'\n\n        elif self.model._meta.model_name == 'virtualmachine':\n            base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)\n            base_query.add((Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None)), Q.AND)\n            base_query.add((Q(clusters=OuterRef('cluster')) | Q(clusters=None)), Q.AND)\n            base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)\n            region_field = 'cluster__site__region'\n\n        base_query.add(\n            (Q(\n                regions__tree_id=OuterRef(f'{region_field}__tree_id'),\n                regions__level__lte=OuterRef(f'{region_field}__level'),\n                regions__lft__lte=OuterRef(f'{region_field}__lft'),\n                regions__rght__gte=OuterRef(f'{region_field}__rght'),\n            ) | Q(regions=None)),\n            Q.AND\n        )\n\n        return base_query\n", "path": "netbox/extras/querysets.py"}], "after_files": [{"content": "from collections import OrderedDict\n\nfrom django.db.models import OuterRef, Subquery, Q\n\nfrom extras.models.tags import TaggedItem\nfrom utilities.query_functions import EmptyGroupByJSONBAgg, OrderableJSONBAgg\nfrom utilities.querysets import RestrictedQuerySet\n\n\nclass CustomFieldQueryset:\n    \"\"\"\n    Annotate custom fields on objects within a QuerySet.\n    \"\"\"\n    def __init__(self, queryset, custom_fields):\n        self.queryset = queryset\n        self.model = queryset.model\n        self.custom_fields = custom_fields\n\n    def __iter__(self):\n        for obj in self.queryset:\n            values_dict = {cfv.field_id: cfv.value for cfv in obj.custom_field_values.all()}\n            obj.custom_fields = OrderedDict([(field, values_dict.get(field.pk)) for field in self.custom_fields])\n            yield obj\n\n\nclass ConfigContextQuerySet(RestrictedQuerySet):\n\n    def get_for_object(self, obj, aggregate_data=False):\n        \"\"\"\n        Return all applicable ConfigContexts for a given object. Only active ConfigContexts will be included.\n\n        Args:\n          aggregate_data: If True, use the JSONBAgg aggregate function to return only the list of JSON data objects\n        \"\"\"\n\n        # `device_role` for Device; `role` for VirtualMachine\n        role = getattr(obj, 'device_role', None) or obj.role\n\n        # Virtualization cluster for VirtualMachine\n        cluster = getattr(obj, 'cluster', None)\n        cluster_group = getattr(cluster, 'group', None)\n\n        # Get the group of the assigned tenant, if any\n        tenant_group = obj.tenant.group if obj.tenant else None\n\n        # Match against the directly assigned region as well as any parent regions.\n        region = getattr(obj.site, 'region', None)\n        if region:\n            regions = region.get_ancestors(include_self=True)\n        else:\n            regions = []\n\n        queryset = self.filter(\n            Q(regions__in=regions) | Q(regions=None),\n            Q(sites=obj.site) | Q(sites=None),\n            Q(roles=role) | Q(roles=None),\n            Q(platforms=obj.platform) | Q(platforms=None),\n            Q(cluster_groups=cluster_group) | Q(cluster_groups=None),\n            Q(clusters=cluster) | Q(clusters=None),\n            Q(tenant_groups=tenant_group) | Q(tenant_groups=None),\n            Q(tenants=obj.tenant) | Q(tenants=None),\n            Q(tags__slug__in=obj.tags.slugs()) | Q(tags=None),\n            is_active=True,\n        ).order_by('weight', 'name').distinct()\n\n        if aggregate_data:\n            return queryset.aggregate(\n                config_context_data=OrderableJSONBAgg('data', ordering=['weight', 'name'])\n            )['config_context_data']\n\n        return queryset\n\n\nclass ConfigContextModelQuerySet(RestrictedQuerySet):\n    \"\"\"\n    QuerySet manager used by models which support ConfigContext (device and virtual machine).\n\n    Includes a method which appends an annotation of aggregated config context JSON data objects. This is\n    implemented as a subquery which performs all the joins necessary to filter relevant config context objects.\n    This offers a substantial performance gain over ConfigContextQuerySet.get_for_object() when dealing with\n    multiple objects.\n\n    This allows the annotation to be entirely optional.\n    \"\"\"\n\n    def annotate_config_context_data(self):\n        \"\"\"\n        Attach the subquery annotation to the base queryset\n        \"\"\"\n        from extras.models import ConfigContext\n        return self.annotate(\n            config_context_data=Subquery(\n                ConfigContext.objects.filter(\n                    self._get_config_context_filters()\n                ).annotate(\n                    _data=EmptyGroupByJSONBAgg('data', ordering=['weight', 'name'])\n                ).values(\"_data\")\n            )\n        ).distinct()\n\n    def _get_config_context_filters(self):\n        # Construct the set of Q objects for the specific object types\n        tag_query_filters = {\n            \"object_id\": OuterRef(OuterRef('pk')),\n            \"content_type__app_label\": self.model._meta.app_label,\n            \"content_type__model\": self.model._meta.model_name\n        }\n        base_query = Q(\n            Q(platforms=OuterRef('platform')) | Q(platforms=None),\n            Q(tenant_groups=OuterRef('tenant__group')) | Q(tenant_groups=None),\n            Q(tenants=OuterRef('tenant')) | Q(tenants=None),\n            Q(\n                tags__pk__in=Subquery(\n                    TaggedItem.objects.filter(\n                        **tag_query_filters\n                    ).values_list(\n                        'tag_id',\n                        flat=True\n                    )\n                )\n            ) | Q(tags=None),\n            is_active=True,\n        )\n\n        if self.model._meta.model_name == 'device':\n            base_query.add((Q(roles=OuterRef('device_role')) | Q(roles=None)), Q.AND)\n            base_query.add((Q(sites=OuterRef('site')) | Q(sites=None)), Q.AND)\n            region_field = 'site__region'\n\n        elif self.model._meta.model_name == 'virtualmachine':\n            base_query.add((Q(roles=OuterRef('role')) | Q(roles=None)), Q.AND)\n            base_query.add((Q(cluster_groups=OuterRef('cluster__group')) | Q(cluster_groups=None)), Q.AND)\n            base_query.add((Q(clusters=OuterRef('cluster')) | Q(clusters=None)), Q.AND)\n            base_query.add((Q(sites=OuterRef('cluster__site')) | Q(sites=None)), Q.AND)\n            region_field = 'cluster__site__region'\n\n        base_query.add(\n            (Q(\n                regions__tree_id=OuterRef(f'{region_field}__tree_id'),\n                regions__level__lte=OuterRef(f'{region_field}__level'),\n                regions__lft__lte=OuterRef(f'{region_field}__lft'),\n                regions__rght__gte=OuterRef(f'{region_field}__rght'),\n            ) | Q(regions=None)),\n            Q.AND\n        )\n\n        return base_query\n", "path": "netbox/extras/querysets.py"}]}