1

I would like to use django-autocomplete-light to autocomplete some fields from an external database that cannot be adjusted to conform to the DjangoORM requirements. Therefore I use SQL Alchemy to connect to this db.

I cannot find out how to do this. As an example I would like to make the autocomplete use the following instead of the Django Model for the table (Which doesn't work because there is a dual column primary key and no id field.

query = (session.query(TableA.FIRSTNAME).distinct(TableA.FIRSTNAME)
                .filter(TableA.FIRSTNAME.match(name)))
data = query.limit(100).all()

Effectively I would like to make the field autocomplete the names from my above query. Instead of using the Django qs as shown in the documentation:

class CountryAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated():
            return Country.objects.none()

        qs = Country.objects.all()

        if self.q:
            qs = qs.filter(name__istartswith=self.q)

        return qs

class PersonForm(forms.ModelForm):
    birth_country = forms.ModelChoiceField(
        queryset=Country.objects.all(),
        widget=autocomplete.ModelSelect2(url='country-autocomplete')
    )
Jonathan Nye
  • 169
  • 9

1 Answers1

2

Ok, I think I managed to find my solution.

I can use the Select2ListView acting upon the SQL Alchemy query which returns a list:

in views.py

from .forms import get_choice_list

class Select2ListViewAutocomplete(autocomplete.Select2ListView):
    def create(self, text):
        return text

    def get_list(self):
        return get_choice_list(name=self.q)

In forms.py I have the following:

from dal import autocomplete

def get_choice_list(name=''):
    return dbc.extract_distinct_typecode(typeCode=name)

class SelectTypeForm(forms.Form):
    typeCode = autocomplete.Select2ListCreateChoiceField(choice_list=get_choice_list, widget=autocomplete.ListSelect2(url='typecode-autocomplete'))

where the dbc.extract_distinct_typecode is the call to a function that uses SQL Alchemy to extract a list of codes. I have limited the length of the list of codes so that the speed is good.

and in urls.py I have the following:

urlpatterns = [
    url(r'^typecode-autocomplete/$', Select2ListViewAutocomplete.as_view(), name='typecode-autocomplete'),]

Its probably a good idea to ensure the user is authenticated so that the url doesn't return the results to any user.

Jonathan Nye
  • 169
  • 9