新建 returns 'list' 对象没有属性 'create'

create new does returns 'list' object has no attribute 'create'

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

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'

我访问自动完成 git 存储库的 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]

有没有比破解代码更好的方法来解决我的问题?

谢谢

在某些情况下,您 return 从 get_queryset 中获取列表,因此该错误不足为奇。

您应该始终return 来自该方法的查询集;你可以 return 一个空的 none():

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