Django REST框架 - get_queryset:' MyModel'对象没有属性' model'

时间:2015-07-12 06:54:39

标签: django django-rest-framework

我在Django REST框架中编辑我的查询集时遇到问题。 基本上我需要过滤我的查询并返回单个查询,因此我的DRF视图如下所示:

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    def get_queryset(self):
        start = self.kwargs['start']
        end = self.kwargs['end']
        qs, created = MyModel.objects.get_or_create(start=start, end=end)
        return qs

所以我返回单个模型实例,但当我尝试获取访问权限时,DRF Web界面出现错误'MyModel' object has no attribute 'model'

回溯:

File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
  85.             return self.dispatch(request, *args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
  456.             response = self.handle_exception(exc)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
  444.             self.initial(request, *args, **kwargs)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in initial
  359.         self.check_permissions(request)
File "/Users/stay-wide-awake/code/env/lib/python3.4/site-packages/rest_framework/views.py" in check_permissions
  304.             if not permission.has_permission(request, self):
File "/Users/stay-wide-awake/code/asp/src/apps/api2/permission.py" in has_permission
  34.         perms = self.get_required_permissions(request.method, queryset.model)

Exception Type: AttributeError at /api/v2/geo/36.606111,-118.062778|36.578581,-120.291994/
Exception Value: 'MyModel' object has no attribute 'model'

路由器和所有其他部件都可以(通过打印测试:))

对任何提示都会感激不尽。

1 个答案:

答案 0 :(得分:4)

通过object收到的MyModel.objects.get_or_create(start=start, end=end)不是查询集,因此您收到此错误。

Django的get_or_create()返回(object, created)元组,其中object是检索或创建的对象,created是一个布尔值,指定是否创建了新对象。

get_queryset()方法中,您将查询集qs设置为此接收的object,而不是其模型对象。

get_queryset()应该返回queryset,而不是您正在做的模型对象。

您可以执行以下操作:

def get_queryset(self):
    start = self.kwargs['start']
    end = self.kwargs['end']
    mymodel_obj, created = MyModel.objects.get_or_create(start=start, end=end)
    return MyModel.objects.filter(id=mymodel_obj.id) # returns a queryset now