【问题标题】:django-autocomplete-light using SQL Alchemy instead of Django ORMdjango-autocomplete-light 使用 SQL Alchemy 而不是 Django ORM
【发布时间】:2017-04-01 08:18:58
【问题描述】:

我想使用 django-autocomplete-light 自动完成来自外部数据库的某些字段,这些字段无法调整以符合 DjangoORM 要求。因此我使用 SQL Alchemy 连接到这个数据库。

我不知道该怎么做。作为一个例子,我想让自动完成使用以下而不是表的 Django 模型(这不起作用,因为有一个双列主键并且没有 id 字段。

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

实际上,我想让该字段自动完成上述查询中的名称。而不是使用文档中显示的 Django qs:

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')
    )

【问题讨论】:

    标签: python django autocomplete django-forms django-autocomplete-light


    【解决方案1】:

    好的,我想我已经找到了解决方案。

    我可以使用 Select2ListView 作用于返回列表的 SQL Alchemy 查询:

    在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)
    

    在 forms.py 我有以下内容:

    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'))
    

    其中 dbc.extract_distinct_typecode 是对使用 SQL Alchemy 提取代码列表的函数的调用。我已经限制了代码列表的长度,以便速度很好。

    在 urls.py 我有以下内容:

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

    确保用户经过身份验证可能是个好主意,这样 url 就不会将结果返回给任何用户。

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 2019-08-12
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2016-09-05
      • 2017-03-26
      • 1970-01-01
      • 2013-01-06
      相关资源
      最近更新 更多