Django Rest Framework'Manager'对象不可下标

时间:2019-05-13 11:33:43

标签: django django-rest-framework django-queryset django-managers

我正在使用自定义查询集作为我的模型的管理器。

class EmployeeQuerySet(QuerySet):
    def update(self, **kwargs):
        # some checks
        super().update(**kwargs)



class EmployeeManager(BaseManager.from_queryset(EmployeeQuerySet)):
    pass


class Employee(models.Model):
    objects = EmployeeManager

(在其他与假期有关的应用程序中)

class Vacation(models.Model):
    employee = models.ForeignKey(Employee)

(度假应用程序具有相当好的标准的Serializer和ViewSet for Vacation Model)。

当我尝试获得/vacation/终点时发生错误。 (DRF浏览的API尝试呈现雇员字段的选择。)

一切正常,但是有a check in django-rest-framework (relations.py)。对于我的模型,此检查失败。实际上,他们正在根据Manager类检查类型,但是我的经理的类型是BaseManager(按预期),而不是Manager

这通过返回管理器而不是queryset触发错误。有什么方法可以使我这一方面成为现实吗? (不是从Manager继承),尽管我认为应该使用DRF中的PR进行更新。

跟踪

  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/django/template/defaulttags.py", line 161, in render
    values = self.sequence.resolve(context, ignore_failures=True)
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/django/template/base.py", line 858, in _resolve_lookup
    current = current()
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/rest_framework/relations.py", line 222, in iter_options
    self.get_choices(cutoff=self.html_cutoff),
  File "/home/nafees/.venvs/shift/lib/python3.7/site-packages/rest_framework/relations.py", line 202, in get_choices
    queryset = queryset[:cutoff]
TypeError: 'EmployeeManager' object is not subscriptable

2 个答案:

答案 0 :(得分:3)

Django文档建议管理器从models.Manager继承,DRF也是如此。

Django documentationBaseManager命名为不是{em> models.BaseManager,而是从models.Manager继承的基本管理器,您可能会感到困惑。 / p>

答案 1 :(得分:0)

您可能正在使用ModelManager而不是Queryset

示例:

Employee.objects ==> Employee.objects.all()