创建新的返回'列表'对象没有属性'创建'

时间:2018-01-10 10:43:18

标签: django django-autocomplete-light

我正在尝试创建一个可以创建新对象的自动完成输入。

class CellLineAutocomplete(autocomplete.Select2QuerySetView):
    create_field = 'cell_line_name'
    model = CellLine
    def has_add_permission(self, request):
        return True

    def get_queryset(self):
        if self.q:
            return CellLine.objects.filter(cell_line_name__icontains=self.q)
        return []

    def get_result_label(self, item):
        return item.cell_line_name

点击create option时收到以下错误:

Traceback (most recent call last):
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 48, in dispatch
    return super(ViewMixin, self).dispatch(request, *args, **kwargs)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 116, in post
    result = self.create_object(text)
  File "/Users/xy/.virtualenvs/z/lib/python3.6/site-packages/dal/views.py", line 92, in create_object
    return self.get_queryset().create(**{self.create_field: text})
AttributeError: 'list' object has no attribute 'create'

我访问autocomplete git repo的code

def create_object(self, text):
    """Create an object given a text."""
    return self.get_queryset().get_or_create(
        **{self.create_field: text})[0]

并编辑它以便为我工作:

def create_object(self, text):
    """Create an object given a text."""
    return self.model.objects.get_or_create(
        **{self.create_field: text})[0]

有没有比通过黑客攻击代码更好的方法来解决我的问题?

由于

1 个答案:

答案 0 :(得分:0)

在某些情况下,您会从get_queryset返回一个列表,因此错误不应该令人惊讶。

您应始终从该方法返回一个查询集;你可以使用none()返回一个空的:

def get_queryset(self):
    if self.q:
        return CellLine.objects.filter(cell_line_name__icontains=self.q)
    return CellLine.objects.none()