如何对大数据使用Django过滤器?

时间:2019-01-24 09:27:48

标签: django django-filter django-filters

我正在将Django-filter与django_filters.ModelChoiceFilter一起使用。我遇到的问题是,如果我在Suburb表中有大量数据,则该网站将非常慢。

class PDetailFilter(django_filters.FilterSet):
class Meta:
    model = PDetail
    fields = {
        # 'code': ['icontains'],
        # 'bu_name': ['icontains'],
        # 'bc_effect_date' : ['year__gt', 'year__lt', ],
    }

# Filter by Suburb
suburb = django_filters.ModelChoiceFilter(label="Suburb", queryset=Suburb.objects.all())

1 个答案:

答案 0 :(得分:0)

最后,我找到了答案。 我正在使用django-autocomplete-light。您可以在此处查看教程:https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html

这是一些源代码 在View.py文件中:

class SuburbAutocomplete(autocomplete.Select2ListView):
def get_list(self):
    # Don't forget to filter out results depending on the visitor !
    # if not self.request.user.is_authenticated():
    #     return Suburb.objects.none()

    qs = Suburb.objects.all()
    if self.q:
        qs = qs.filter(suburb__istartswith=self.q)
    return qs

在Filters.py

# Filter by Suburb
suburb = django_filters.ModelChoiceFilter(
label="Suburb",
queryset=Suburb.objects.all(), 
widget=autocomplete.ModelSelect2(
    url='backend:suburb-autocomplete',
    attrs={
            # Set some placeholder
            'data-placeholder': 'Suburb ...',
            # Only trigger autocompletion after 2 characters have been typed
            'data-minimum-input-length': 2,
            'style': 'height:34px !important;'
        },
    )
)