将特定字段的查询集返回给自动完成的表单字段

时间:2020-01-28 07:59:15

标签: django django-queryset

我不是django专家,所以我不确定是否只是在搜索错误的内容,但是我正在尝试使用django-autocomplete-light自动完成模型表单上的某些字段。

我有一个动物模型。动物有几个领域。我的目标是拥有一个可以自动完成其中几个字段的模型形式。

forms.py

class AnimalForm(ModelForm):
class Meta:
    model = Animal
    fields = [
        'myfield'
    ]
    widgets = {
        'myfield': autocomplete.ListSelect2(
            url='myfield-autocomplete')
    }

views.py:

class MyfieldAutocomplete(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 Animal.objects.none()
        qs = Animal.objects.filter().values('myfield')
        if self.q:
            qs = qs.filter(name__istartswith=self.q)
        return qs

我得到:

AttributeError: 'dict' object has no attribute 'pk'

我认为是因为Animal.objects.filter()。values('myfield')返回的是实际值,而不是查询集。

如果我将查询集更改为:

class MyfieldAutocomplete(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 Animal.objects.none()
        qs = Animal.objects.all()
        if self.q:
            qs = qs.filter(name__istartswith=self.q)
        return qs

这将加载,并且我的自动完成字段将填充“动物”对象的名称字段。我希望能够指定一个任意字段而不是名称。

更新- 错误输出:

[28/Jan/2020 08:02:33] "GET /animals/add HTTP/1.1" 200 47686
C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py:88: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'animals.models.Animal'> QuerySet.
  allow_empty_first_page=allow_empty_first_page, **kwargs)
Internal Server Error: /operator-autocomplete/
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response        
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response        
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dal\views.py", line 50, in dispatch
    return super(ViewMixin, self).dispatch(request, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py", line 158, in get
    return self.render_to_response(context)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dal_select2\views.py", line 61, in render_to_response
    'results': self.get_results(context) + create_option,
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dal_select2\views.py", line 26, in get_results
    } for result in context['object_list']
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dal_select2\views.py", line 26, in <listcomp>
    } for result in context['object_list']
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\dal\views.py", line 81, in get_result_value
    return str(result.pk)
AttributeError: 'dict' object has no attribute 'pk'

1 个答案:

答案 0 :(得分:1)

如果您想为特定字段进行自动完成,而不是charfield,则将该字段设置为外键并实现自动完成。例如,如果您在Animal类中有一个名为dog的字段,则创建一个Dog类并以以下形式进行操作

class AnimalCreateForm(forms.ModelForm):
    dog = forms.ModelChoiceField(
        queryset=Dog.objects.all(),
        widget=autocomplete.ModelSelect2(url='dog_auto')
    )
    class Meta:
        model = Animal
        fields = [
        'dog', ----,
    ]