We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error 500 by search a Parent
Hi
I become an 500 error when i will search a Parent by hardware under Data center (When I click on the magnifying glass).

Here is the code:

```
AssertionError at /data_center/datacenterasset/
Cannot combine a unique query with a non-unique query.
Request Method: GET
Request URL:    http://myip/data_center/datacenterasset/?_to_field=id&_popup=1
Django Version: 1.8.9
Exception Type: AssertionError
Exception Value:    
Cannot combine a unique query with a non-unique query.
Exception Location: /opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/sql/query.py in combine, line 500
Python Executable:  /opt/ralph/ralph-core/bin/python
Python Version: 3.4.3
Python Path:    
['/opt/ralph/ralph-core/bin',
 '/opt/ralph/ralph-core/lib/python3.4',
 '/opt/ralph/ralph-core/lib/python3.4/plat-x86_64-linux-gnu',
 '/opt/ralph/ralph-core/lib/python3.4/lib-dynload',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/opt/ralph/ralph-core/lib/python3.4/site-packages']
Server time:    Fri, 26 Feb 2016 10:00:06 +0100

Environment:


Request Method: GET
Request URL: http://myip/data_center/datacenterasset/?_to_field=id&_popup=1

Django Version: 1.8.9
Python Version: 3.4.3
Installed Applications:
('ralph.admin',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.humanize',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'import_export',
 'mptt',
 'reversion',
 'sitetree',
 'ralph.accounts',
 'ralph.assets',
 'ralph.attachments',
 'ralph.back_office',
 'ralph.data_center',
 'ralph.licences',
 'ralph.domains',
 'ralph.supports',
 'ralph.lib.foundation',
 'ralph.lib.table',
 'ralph.data_importer',
 'ralph.dc_view',
 'ralph.reports',
 'ralph.lib.transitions',
 'ralph.lib.permissions',
 'rest_framework',
 'rest_framework.authtoken',
 'taggit',
 'taggit_serializer')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.4/contextlib.py" in inner
  30.                 return func(*args, **kwds)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/reversion/revisions.py" in do_revision_context
  297.                 return func(*args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/mixins.py" in changelist_view
  187.             request, extra_context
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/reversion/admin.py" in changelist_view
  419.         return super(VersionAdmin, self).changelist_view(request, context)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/options.py" in changelist_view
  1550.                 self.list_max_show_all, self.list_editable, self)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/views/main.py" in __init__
  14.         super().__init__(request, *args, **kwargs)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/views/main.py" in __init__
  81.         self.queryset = self.get_queryset(request)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/views/main.py" in get_queryset
  66.                 queryset = queryset & autocomplete_queryset()
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/query.py" in __and__
  211.         combined.query.combine(other.query, sql.AND)
File "/opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/sql/query.py" in combine
  500.             "Cannot combine a unique query with a non-unique query."

Exception Type: AssertionError at /data_center/datacenterasset/
Exception Value: Cannot combine a unique query with a non-unique query.
```

Thanks for help.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/ralph/admin/views/main.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 from django.contrib.admin.views.main import ChangeList
3 
4 SEARCH_SCOPE_VAR = 'search-scope'
5 BULK_EDIT_VAR = 'bulk_edit'
6 BULK_EDIT_VAR_IDS = 'id'
7 IGNORED_FIELDS = (BULK_EDIT_VAR, BULK_EDIT_VAR_IDS, SEARCH_SCOPE_VAR)
8 
9 
10 class RalphChangeList(ChangeList):
11 
12     def __init__(self, request, *args, **kwargs):
13         self.bulk_edit = request.GET.get(BULK_EDIT_VAR, False)
14         super().__init__(request, *args, **kwargs)
15 
16     def get_filters_params(self, params=None):
17         result = super().get_filters_params(params)
18         for field in IGNORED_FIELDS:
19             if field in result:
20                 del result[field]
21         return result
22 
23     def get_ordering_from_related_model_admin(self, prefix, field_name):
24         """
25         Get ordering from related model admin.
26         """
27         admin_site = self.model_admin.admin_site
28         field = getattr(self.model, field_name, None)
29         fields = [prefix + field_name]
30         if not field:
31             return fields
32         try:
33             model_admin = admin_site._registry[field.field.rel.to]
34         except AttributeError:
35             pass
36         else:
37             if all([model_admin, model_admin.ordering]):
38                 fields = [
39                     '{}{}__{}'.format(prefix, field_name, order.lstrip('-'))
40                     for order in model_admin.ordering
41                 ]
42         return fields
43 
44     def get_ordering(self, request, queryset):
45         """
46         Extends ordering list by list fetching from related model admin.
47         """
48         old_ordering = super().get_ordering(request, queryset)
49         ordering = []
50         for field_order in old_ordering:
51             _, prefix, field = field_order.rpartition('-')
52             ordering.extend(
53                 self.get_ordering_from_related_model_admin(prefix, field)
54             )
55         return ordering
56 
57     def get_queryset(self, request):
58         queryset = super().get_queryset(request)
59         if self.is_popup:
60             # For popup window we limit display of records to the same as
61             # we have in the autocomplete widget.
62             autocomplete_queryset = getattr(
63                 self.model, 'get_autocomplete_queryset', None
64             )
65             if autocomplete_queryset:
66                 queryset = queryset & autocomplete_queryset()
67         return queryset
68
```
--- 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/src/ralph/admin/views/main.py b/src/ralph/admin/views/main.py
--- a/src/ralph/admin/views/main.py
+++ b/src/ralph/admin/views/main.py
@@ -63,5 +63,18 @@
                 self.model, 'get_autocomplete_queryset', None
             )
             if autocomplete_queryset:
-                queryset = queryset & autocomplete_queryset()
+                autocomplete_queryset = autocomplete_queryset()
+                # #2248 - cannot combine unique (distinct) and non-unique query
+                # if one of the queries is distinct, make sure all are distinct
+                if (
+                    queryset.query.distinct and
+                    not autocomplete_queryset.query.distinct
+                ):
+                    autocomplete_queryset = autocomplete_queryset.distinct()
+                if (
+                    not queryset.query.distinct and
+                    autocomplete_queryset.query.distinct
+                ):
+                    queryset = queryset.distinct()
+                queryset = queryset & autocomplete_queryset
         return queryset

{"golden_diff": "diff --git a/src/ralph/admin/views/main.py b/src/ralph/admin/views/main.py\n--- a/src/ralph/admin/views/main.py\n+++ b/src/ralph/admin/views/main.py\n@@ -63,5 +63,18 @@\n                 self.model, 'get_autocomplete_queryset', None\n             )\n             if autocomplete_queryset:\n-                queryset = queryset & autocomplete_queryset()\n+                autocomplete_queryset = autocomplete_queryset()\n+                # #2248 - cannot combine unique (distinct) and non-unique query\n+                # if one of the queries is distinct, make sure all are distinct\n+                if (\n+                    queryset.query.distinct and\n+                    not autocomplete_queryset.query.distinct\n+                ):\n+                    autocomplete_queryset = autocomplete_queryset.distinct()\n+                if (\n+                    not queryset.query.distinct and\n+                    autocomplete_queryset.query.distinct\n+                ):\n+                    queryset = queryset.distinct()\n+                queryset = queryset & autocomplete_queryset\n         return queryset\n", "issue": "Error 500 by search a Parent\nHi\nI become an 500 error when i will search a Parent by hardware under Data center (When I click on the magnifying glass).\n\nHere is the code:\n\n```\nAssertionError at /data_center/datacenterasset/\nCannot combine a unique query with a non-unique query.\nRequest Method: GET\nRequest URL:    http://myip/data_center/datacenterasset/?_to_field=id&_popup=1\nDjango Version: 1.8.9\nException Type: AssertionError\nException Value:    \nCannot combine a unique query with a non-unique query.\nException Location: /opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/sql/query.py in combine, line 500\nPython Executable:  /opt/ralph/ralph-core/bin/python\nPython Version: 3.4.3\nPython Path:    \n['/opt/ralph/ralph-core/bin',\n '/opt/ralph/ralph-core/lib/python3.4',\n '/opt/ralph/ralph-core/lib/python3.4/plat-x86_64-linux-gnu',\n '/opt/ralph/ralph-core/lib/python3.4/lib-dynload',\n '/usr/lib/python3.4',\n '/usr/lib/python3.4/plat-x86_64-linux-gnu',\n '/opt/ralph/ralph-core/lib/python3.4/site-packages']\nServer time:    Fri, 26 Feb 2016 10:00:06 +0100\n\nEnvironment:\n\n\nRequest Method: GET\nRequest URL: http://myip/data_center/datacenterasset/?_to_field=id&_popup=1\n\nDjango Version: 1.8.9\nPython Version: 3.4.3\nInstalled Applications:\n('ralph.admin',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.humanize',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'import_export',\n 'mptt',\n 'reversion',\n 'sitetree',\n 'ralph.accounts',\n 'ralph.assets',\n 'ralph.attachments',\n 'ralph.back_office',\n 'ralph.data_center',\n 'ralph.licences',\n 'ralph.domains',\n 'ralph.supports',\n 'ralph.lib.foundation',\n 'ralph.lib.table',\n 'ralph.data_importer',\n 'ralph.dc_view',\n 'ralph.reports',\n 'ralph.lib.transitions',\n 'ralph.lib.permissions',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'taggit',\n 'taggit_serializer')\nInstalled Middleware:\n('django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware')\n\n\nTraceback:\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/core/handlers/base.py\" in get_response\n  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)\nFile \"/usr/lib/python3.4/contextlib.py\" in inner\n  30.                 return func(*args, **kwds)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/options.py\" in wrapper\n  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py\" in _wrapped_view\n  110.                     response = view_func(request, *args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/views/decorators/cache.py\" in _wrapped_view_func\n  57.         response = view_func(request, *args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/sites.py\" in inner\n  233.             return view(request, *args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/reversion/revisions.py\" in do_revision_context\n  297.                 return func(*args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/mixins.py\" in changelist_view\n  187.             request, extra_context\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/reversion/admin.py\" in changelist_view\n  419.         return super(VersionAdmin, self).changelist_view(request, context)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py\" in _wrapper\n  34.             return bound_func(*args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py\" in _wrapped_view\n  110.                     response = view_func(request, *args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/utils/decorators.py\" in bound_func\n  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/options.py\" in changelist_view\n  1550.                 self.list_max_show_all, self.list_editable, self)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/views/main.py\" in __init__\n  14.         super().__init__(request, *args, **kwargs)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/contrib/admin/views/main.py\" in __init__\n  81.         self.queryset = self.get_queryset(request)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/ralph/admin/views/main.py\" in get_queryset\n  66.                 queryset = queryset & autocomplete_queryset()\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/query.py\" in __and__\n  211.         combined.query.combine(other.query, sql.AND)\nFile \"/opt/ralph/ralph-core/lib/python3.4/site-packages/django/db/models/sql/query.py\" in combine\n  500.             \"Cannot combine a unique query with a non-unique query.\"\n\nException Type: AssertionError at /data_center/datacenterasset/\nException Value: Cannot combine a unique query with a non-unique query.\n```\n\nThanks for help.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nfrom django.contrib.admin.views.main import ChangeList\n\nSEARCH_SCOPE_VAR = 'search-scope'\nBULK_EDIT_VAR = 'bulk_edit'\nBULK_EDIT_VAR_IDS = 'id'\nIGNORED_FIELDS = (BULK_EDIT_VAR, BULK_EDIT_VAR_IDS, SEARCH_SCOPE_VAR)\n\n\nclass RalphChangeList(ChangeList):\n\n    def __init__(self, request, *args, **kwargs):\n        self.bulk_edit = request.GET.get(BULK_EDIT_VAR, False)\n        super().__init__(request, *args, **kwargs)\n\n    def get_filters_params(self, params=None):\n        result = super().get_filters_params(params)\n        for field in IGNORED_FIELDS:\n            if field in result:\n                del result[field]\n        return result\n\n    def get_ordering_from_related_model_admin(self, prefix, field_name):\n        \"\"\"\n        Get ordering from related model admin.\n        \"\"\"\n        admin_site = self.model_admin.admin_site\n        field = getattr(self.model, field_name, None)\n        fields = [prefix + field_name]\n        if not field:\n            return fields\n        try:\n            model_admin = admin_site._registry[field.field.rel.to]\n        except AttributeError:\n            pass\n        else:\n            if all([model_admin, model_admin.ordering]):\n                fields = [\n                    '{}{}__{}'.format(prefix, field_name, order.lstrip('-'))\n                    for order in model_admin.ordering\n                ]\n        return fields\n\n    def get_ordering(self, request, queryset):\n        \"\"\"\n        Extends ordering list by list fetching from related model admin.\n        \"\"\"\n        old_ordering = super().get_ordering(request, queryset)\n        ordering = []\n        for field_order in old_ordering:\n            _, prefix, field = field_order.rpartition('-')\n            ordering.extend(\n                self.get_ordering_from_related_model_admin(prefix, field)\n            )\n        return ordering\n\n    def get_queryset(self, request):\n        queryset = super().get_queryset(request)\n        if self.is_popup:\n            # For popup window we limit display of records to the same as\n            # we have in the autocomplete widget.\n            autocomplete_queryset = getattr(\n                self.model, 'get_autocomplete_queryset', None\n            )\n            if autocomplete_queryset:\n                queryset = queryset & autocomplete_queryset()\n        return queryset\n", "path": "src/ralph/admin/views/main.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nfrom django.contrib.admin.views.main import ChangeList\n\nSEARCH_SCOPE_VAR = 'search-scope'\nBULK_EDIT_VAR = 'bulk_edit'\nBULK_EDIT_VAR_IDS = 'id'\nIGNORED_FIELDS = (BULK_EDIT_VAR, BULK_EDIT_VAR_IDS, SEARCH_SCOPE_VAR)\n\n\nclass RalphChangeList(ChangeList):\n\n    def __init__(self, request, *args, **kwargs):\n        self.bulk_edit = request.GET.get(BULK_EDIT_VAR, False)\n        super().__init__(request, *args, **kwargs)\n\n    def get_filters_params(self, params=None):\n        result = super().get_filters_params(params)\n        for field in IGNORED_FIELDS:\n            if field in result:\n                del result[field]\n        return result\n\n    def get_ordering_from_related_model_admin(self, prefix, field_name):\n        \"\"\"\n        Get ordering from related model admin.\n        \"\"\"\n        admin_site = self.model_admin.admin_site\n        field = getattr(self.model, field_name, None)\n        fields = [prefix + field_name]\n        if not field:\n            return fields\n        try:\n            model_admin = admin_site._registry[field.field.rel.to]\n        except AttributeError:\n            pass\n        else:\n            if all([model_admin, model_admin.ordering]):\n                fields = [\n                    '{}{}__{}'.format(prefix, field_name, order.lstrip('-'))\n                    for order in model_admin.ordering\n                ]\n        return fields\n\n    def get_ordering(self, request, queryset):\n        \"\"\"\n        Extends ordering list by list fetching from related model admin.\n        \"\"\"\n        old_ordering = super().get_ordering(request, queryset)\n        ordering = []\n        for field_order in old_ordering:\n            _, prefix, field = field_order.rpartition('-')\n            ordering.extend(\n                self.get_ordering_from_related_model_admin(prefix, field)\n            )\n        return ordering\n\n    def get_queryset(self, request):\n        queryset = super().get_queryset(request)\n        if self.is_popup:\n            # For popup window we limit display of records to the same as\n            # we have in the autocomplete widget.\n            autocomplete_queryset = getattr(\n                self.model, 'get_autocomplete_queryset', None\n            )\n            if autocomplete_queryset:\n                autocomplete_queryset = autocomplete_queryset()\n                # #2248 - cannot combine unique (distinct) and non-unique query\n                # if one of the queries is distinct, make sure all are distinct\n                if (\n                    queryset.query.distinct and\n                    not autocomplete_queryset.query.distinct\n                ):\n                    autocomplete_queryset = autocomplete_queryset.distinct()\n                if (\n                    not queryset.query.distinct and\n                    autocomplete_queryset.query.distinct\n                ):\n                    queryset = queryset.distinct()\n                queryset = queryset & autocomplete_queryset\n        return queryset\n", "path": "src/ralph/admin/views/main.py"}]}