python django-autocomplete-light UnorderedObjectListWarning

时间:2018-04-11 01:26:18

标签: django django-autocomplete-light

我最近使用Django做网站,我在实现链式下拉/依赖下拉时遇到了困难。我尝试过智能选择,但无法实现它,当我偶然发现django-autocomplete-light时。

我能够实现这个并且它符合我当前的要求,但是,我注意到python正在抛出这个警告:

UnorderedObjectListWarning: Pagination may yield inconsistent results
with an unordered object_list: <class 'project.models.Driver'> QuerySet.

我彻底遵循了django-autocomplete-light中的教程,但我仍然遗漏了一些内容。

forms.py

class TripModelForm(forms.ModelForm):

    driver = forms.ModelChoiceField(
        queryset=Driver.objects.all(),
        widget=autocomplete.ModelSelect2(url='driver_autocomplete',
                                         forward=['hauler'])
    )

    class Meta:
        model = Trip
        fields = ['ticket', 'date_issued', 'department', 'hauler', 'plate_number', 'driver',]

urls.py

urlpatterns += [
    path('driver-autocomplete/', views.DriverAutocomplete.as_view(), name='driver_autocomplete'),
]

views.py

class DriverAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        if not self.request.user.is_authenticated():
            return Driver.objects.none()

        qs = Driver.objects.all()
        hauler = self.forwarded.get('hauler', None)

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

        return qs

1 个答案:

答案 0 :(得分:1)

我跟着错误来自哪里\ python36 \ lib \ site-packages \ django \ views \ generic \ list.py:88。看起来这个类需要有序的查询集,所以我将views.py修改为:

<强> views.py

class DriverAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        if not self.request.user.is_authenticated():
        return Driver.objects.none()

        qs = Driver.objects.all().order_by('name') <-- here
        if self.q:
        hauler = self.forwarded.get('hauler', None)

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

        return qs

此解决方案对我有用,我可以通过删除查询中的.order_by来复制警告。