Repository: yourlabs/django-autocomplete-light
Issue: Inline autocomplete breaking 

I have no real idea why this would be breaking, I am just using a simple autocomplete in an inline and getting this error

```
missing FROM-clause entry for table "subjects_subject"
LINE 1: SELECT (CASE WHEN Subjects_subject.id='1' THEN 0 END) AS "or...
```

any help is appreciate, here is traceback

Environment:

``````
Request Method: POST
Request URL: http://104.236.221.79/admin/Tutor/tutorstudentrelationship/12/

Django Version: 1.8.2
Python Version: 2.7.6
Installed Applications:
('autocomplete_light',
 'favicon',
 'wpadmin',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'apptemplates',
 'jquery',
 'crispy_forms',
 'bootstrap3',
 'localflavor',
 'datetimewidget',
 'fm',
 'django_fsm',
 'fsm_admin',
 'djwkhtmltopdf',
 'schedule',
 'easymoney',
 'phonenumber_field',
 'django_countries',
 'postal',
 'babel',
 'easy_thumbnails',
 'timezone_field',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'Accounting',
 'Billing',
 'GroupInvitations',
 'BrownstoneTutors',
 'Sessions',
 'Student',
 'Tutor',
 'Client',
 'Subjects')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.locale.LocaleMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
  616.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view
  1519.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in inner
  145.                     return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view
  1466.             if all_valid(formsets) and form_validated:
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in all_valid
  439.         if not formset.is_valid():
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in is_valid
  304.         self.errors
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in errors
  278.             self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/formsets.py" in full_clean
  327.             self._errors.append(form.errors)
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in errors
  176.             self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in full_clean
  392.         self._clean_fields()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in _clean_fields
  407.                     value = field.clean(value)
File "/usr/local/lib/python2.7/dist-packages/django/forms/fields.py" in clean
  163.         self.validate(value)
File "/usr/local/lib/python2.7/dist-packages/autocomplete_light/fields.py" in validate
  61.         if value and not self.autocomplete(values=values).validate_values():
File "/usr/local/lib/python2.7/dist-packages/autocomplete_light/autocomplete/model.py" in validate_values
  169.         return len(self.choices_for_values()) == len(self.values)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __len__
  144.         self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _fetch_all
  965.             self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in iterator
  238.         results = compiler.execute_sql()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /admin/Tutor/tutorstudentrelationship/12/
Exception Value: missing FROM-clause entry for table "subjects_subject"
LINE 1: SELECT (CASE WHEN Subjects_subject.id='1' THEN 0 END) AS "or...
```                          ^

``````


Changed files:
autocomplete_light/tests/autocomplete/test_model.py, autocomplete_light/example_apps/autocomplete_test_case_app/models.py, autocomplete_light/autocomplete/model.py

diff --git a/autocomplete_light/autocomplete/model.py b/autocomplete_light/autocomplete/model.py
index 0b36ef1..2b5c4e4 100644
--- a/autocomplete_light/autocomplete/model.py
+++ b/autocomplete_light/autocomplete/model.py
@@ -3,6 +3,7 @@ from __future__ import unicode_literals
 import six
 from django.db.models import Q
 from django.utils.encoding import force_text
+from django.db import connection
 
 from ..settings import DEFAULT_SEARCH_FIELDS
 
@@ -72,7 +73,10 @@ class AutocompleteModel(object):
         if self.values:
             pk_name = ('id' if not getattr(choices.model._meta, 'pk', None)
                     else choices.model._meta.pk.column)
-            pk_name = '%s.%s' % (choices.model._meta.db_table, pk_name)
+
+            field = '"%s"."%s"' if connection.vendor == 'postgresql' \\
+                    else '%s.%s'
+            pk_name = field % (choices.model._meta.db_table, pk_name)
 
             # Order in the user selection order when self.values is set.
             clauses = ' '.join(['WHEN %s=\\'%s\\' THEN %s' % (pk_name, pk, i)
diff --git a/autocomplete_light/example_apps/autocomplete_test_case_app/models.py b/autocomplete_light/example_apps/autocomplete_test_case_app/models.py
index 92d554f..2539d25 100644
--- a/autocomplete_light/example_apps/autocomplete_test_case_app/models.py
+++ b/autocomplete_light/example_apps/autocomplete_test_case_app/models.py
@@ -33,3 +33,11 @@ class CustomSchema(models.Model):
 
     class Meta:
         db_table = 'foobar'
+
+
+class Caps(models.Model):
+    id = models.IntegerField(primary_key=True, db_column='Id')
+    name = models.CharField(max_length=10, db_column='Bar')
+
+    class Meta:
+        db_table = 'Caps'
diff --git a/autocomplete_light/tests/autocomplete/test_model.py b/autocomplete_light/tests/autocomplete/test_model.py
index 24856c8..314a369 100644
--- a/autocomplete_light/tests/autocomplete/test_model.py
+++ b/autocomplete_light/tests/autocomplete/test_model.py
@@ -7,7 +7,7 @@ from django import VERSION
 from django.utils.encoding import force_text
 
 from autocomplete_light.example_apps.autocomplete_test_case_app.models import (
-        NonIntegerPk, SubGroup, CustomSchema, CustomIntegerPk)
+        NonIntegerPk, SubGroup, CustomSchema, CustomIntegerPk, Caps)
 from .case import *
 
 
@@ -223,3 +223,12 @@ class AutocompleteModelTestCase(AutocompleteTestCase):
 
         fixture = Fixture(values=[1, 4])
         self.assertEqual(list(fixture.choices_for_values()), [self.abe, self.john])
+
+    def test_caps(self):
+        obj = Caps.objects.create(id=7, name='test')
+
+        class Test(autocomplete_light.AutocompleteModelBase):
+            choices = Caps.objects.all()
+
+        fixture = Test(values=[obj.pk])
+        assert fixture.choices_for_values()[0] == obj