django rest framework error无法在未设置`.queryset`或具有`.get_queryset()`方法

时间:2016-04-06 05:59:44

标签: python django rest

我正在使用django 1.9.5和休息框架3.x(DRF)。我刚刚从官方django rest框架开始学习教程,你可以说它已经开始使用DRF了,我已经写了 views < / em>, urls 了解api如何使用DRF,

视图

class DepartMentList(APIView):
    """
    List of all departments or create a department
    """

    def get(self, request, format=None):
        departments = Department.objects.all()
        serializer = DepartmentSerializer(departments)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DepartmentSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return   Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST)

网址

from django.conf.urls import url

from rest_framework.urlpatterns import format_suffix_patterns

from organizations import views

    urlpatterns = [
        url(r'^departments/$', views.DepartMentList.as_view()),
    ]

    urlpatterns = format_suffix_patterns(urlpatterns)

这是我在为DEFAULT_PERMISSION_CLASSES添加以下rest framework dict的setting.py

REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]

}

现在,当我为部门运行endpoint以查看部门列表时,我收到以下错误,

'Cannot apply DjangoModelPermissions on a view that '
AssertionError: Cannot apply DjangoModelPermissions on a view that does not set `.queryset` or have a `.get_queryset()` method.

实际导致错误的是什么?我已经调查过,但无法弄清楚。

更新

class DepartMentDetail(APIView):
    """
    Retrieve, update or delete a department instance.
    """

    def get_object(self, pk):

        try:
            return Department.objects.get(pk=pk)
        except Department.DoesNotExist:
            raise Http404

    def get(self,request,pk,format=None):

        department = self.get_object(pk)
        serializer = DepartmentSerializer(department)
        return Response(serializer.data)

    def put(self,request,pk,format=None):
        department = self.get_object(pk)
        serializer = DepartmentSerializer(department,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        department = self.get_object(pk)
        department.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

1 个答案:

答案 0 :(得分:3)

DjangoRestFramework要求您在视图中设置queryset类参数或实现get_queryset方法。它在应用权限类时检查它。由于DjangoModelPermissionsOrAnonReadOnly具有has_permission方法,如下所示,此方法会检查您的视图是否包含queryset变量或get_queryset方法。

def has_permission(self, request, view):
    # Workaround to ensure DjangoModelPermissions are not applied
    # to the root view when using DefaultRouter.
    if getattr(view, '_ignore_model_permissions', False):
        return True

    if hasattr(view, 'get_queryset'):
        queryset = view.get_queryset()
    else:
        queryset = getattr(view, 'queryset', None)

    assert queryset is not None, (
        'Cannot apply DjangoModelPermissions on a view that '
        'does not set `.queryset` or have a `.get_queryset()` method.'
    )

    perms = self.get_required_permissions(request.method, queryset.model)

    return (
        request.user and
        (request.user.is_authenticated() or not self.authenticated_users_only) and
        request.user.has_perms(perms)
    )

如您所见,has_permission方法为assert变量生成queryset 您的视图应如下所示

class DepartMentList(APIView):
    """
    List of all departments or create a department
    """
    queryset = Department.objects.all()

    def get(self, request, format=None):
        serializer = DepartmentSerializer(self.queryset)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DepartmentSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return   Response(serializer.data,status=status.HTTP_201_CREATED)
        return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST)

P.S使用http://www.django-rest-framework.org/api-guide/generic-views/它更清洁))