关于python:Django – get_queryset()缺少1个必需的位置参数:’request’

Django - get_queryset() missing 1 required positional argument: 'request'

我尝试使用REST框架创建一个API,用于将文件上载到服务器,我的代码如下。

如果您还有其他简单的方法可以做到这一点,请发布您的代码。

型号.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.db import models

# Create your models here.

class FileUploader(models.Model):
    file = models.FileField()
    name = models.CharField(max_length=100) #name is filename without extension
    version = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now=True, db_index=True)
    owner = models.ForeignKey('auth.User', related_name='uploaded_files')
    size = models.IntegerField(default=0)

    def __str__(self):
        return self.name

序列化程序.py

1
2
3
4
5
6
7
8
9
10
11
12
class FileUploaderSerializer(serializers.ModelSerializer):
    class Meta:
        model=FileUploader
        fields='__all__'
        read_only_fields = '__all__'
    def validate(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
        validated_data['size'] = validated_data['file'].size
        return validated_data
    def create(self,validated_data):
        return FileUploader.objects.create(**validated_data)

视图.py

1
2
3
4
5
6
7
class FileUploaderViewSet(viewsets.ModelViewSet):
    serializer_class = FileUploaderSerializer
    parser_classes=(MultiPartParser,FormParser)
    def get_queryset(self,request, *args, **kwargs):
        qs = super(FileUploaderViewSet, self).get_queryset(self,request, *args, **kwargs)
        qs = qs.filter(owner=self.request.user)
        return qs

网址.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.conf.urls import url
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
from webapp.views import(
    UserCreateAPIView,
    UserLoginAPIView,
    FileUploaderViewSet,
    )

router = routers.DefaultRouter()
router.register(r'upload', views.FileUploaderViewSet,base_name='file-view')

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(router.urls)),
    #url(r'^upload/$',FileUploaderViewSet.as_view()),

]

我的要求是我需要上传一个文件到服务器,并显示上传文件的详细信息。

这就是我犯的错误!

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File"F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File"F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())

Exception Type: TypeError at /upload/ Exception Value: get_queryset()
missing 1 required positional argument: 'request'

更新的views.py文件如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser

from rest_framework import viewsets
from rest_framework.status import HTTP_200_OK,HTTP_400_BAD_REQUEST
from .models import employees
from .serializers import (
    employeesSerializer,
    FileUploaderSerializer,
    )
from django.contrib.auth import get_user_model
from rest_framework.generics import (
    CreateAPIView,
    DestroyAPIView,
    ListAPIView,
    RetrieveAPIView,
    RetrieveUpdateAPIView,
    )

from rest_framework.permissions import(
    AllowAny,
    IsAuthenticated,
    IsAdminUser,
    IsAuthenticatedOrReadOnly,
    )

class employeeList(APIView):
    def get(self,request):
        employees1=employees.objects.all()
        serializer=employeesSerializer(employees1,many=True)
        return Response(serializer.data)


    def post(self):
        pass

User=get_user_model()

from .serializers import(
    UserCreateSerializer,
    UserLoginSerializer,
    )

class UserCreateAPIView(CreateAPIView):
    serializer_class=UserCreateSerializer
    queryset=User.objects.all()


class UserLoginAPIView(APIView):
    permission_classes=[AllowAny]
    serializer_class=UserLoginSerializer
    def post(self,request,*args,**kwargs):
        data=request.data
        serializer=UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data=serializer.data
            return Response(new_data,status=HTTP_200_OK)
        return Response(serializer.errors,status=HTTP_400_BAD_REQUEST)

class FileUploaderViewSet(viewsets.ModelViewSet):
    serializer_class = FileUploaderSerializer
    parser_classes=(MultiPartParser,FormParser)

 # overriding default query set
    #queryset = LayerFile.objects.all()

    def get_queryset(self, *args, **kwargs):
        qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)
        qs = qs.filter(owner=self.request.user)
        return qs

回溯:

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File"F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File"F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())

File"F:\proj\env\myproject\webapp\views.py" in get_queryset
74. qs = super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)

Exception Type: TypeError at /upload/ Exception Value: get_queryset()
takes 1 positional argument but 2 were given

更改get查询集后新建跟踪

1
2
3
4
5
6
7
8
9
10
class FileUploaderViewSet(viewsets.ModelViewSet):
    serializer_class = FileUploaderSerializer
    parser_classes=(MultiPartParser,FormParser)

 # overriding default query set

    def get_queryset(self):
        qs = super(FileUploaderViewSet, self).get_queryset()
        qs = qs.filter(owner=self.request.user)
        return qs

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/upload/

Django Version: 1.11.7 Python Version: 3.6.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'rest_framework', 'webapp'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File"F:\proj\env\lib\site-packages\django\core\handlers\exception.py"
in inner
41. response = get_response(request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
187. response = self.process_exception_by_middleware(e, request)

File"F:\proj\env\lib\site-packages\django\core\handlers\base.py" in
_get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File"F:\proj\env\lib\site-packages\django\views\decorators\csrf.py"
in wrapped_view
58. return view_func(*args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\viewsets.py" in
view
90. return self.dispatch(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
489. response = self.handle_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
handle_exception
449. self.raise_uncaught_exception(exc)

File"F:\proj\env\lib\site-packages
est_framework\views.py" in
dispatch
486. response = handler(request, *args, **kwargs)

File"F:\proj\env\lib\site-packages
est_framework\mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())

File"F:\proj\env\myproject\webapp\views.py" in get_queryset
74. qs = super(FileUploaderViewSet, self).get_queryset()

File"F:\proj\env\lib\site-packages
est_framework\generics.py" in
get_queryset
68. % self.class.name

Exception Type: AssertionError at /upload/ Exception Value:
'FileUploaderViewSet' should either include a queryset attribute, or
override the get_queryset() method.


正如赛斯所说,它只需要self。但你不必把self传给get_queryset()self只是一个实例,super本身就是一个自实例。

所以只要把你的下一行从

1
super(FileUploaderViewSet, self).get_queryset(self, *args, **kwargs)

1
super(FileUploaderViewSet, self).get_queryset()

请看这里的代码段

更新:

你确定,你的get_queryset是同一班的吗?

你刚刚试着写了queryset = Model.objects.all()吗?

我看不到你的看法。

view class应具有以下字段。

1
2
3
4
5
def get_queryset(self):
    return queryset

serializer_class = SerializerClass
model = ModelName


get_queryset()不需要"请求"。可能从get_queryset()中移除'request'参数。作为参考,您可以检查:获取查询集()

可能是这样的:

1
2
3
4
def get_queryset(self, *args, **kwargs):
    qs = your_model.objects.all()
    qs = qs.filter(owner=self.request.user)
    return qs


get_queryset不需要请求参数,它不会由drf基类传递。但是,它作为实例属性可用。您应该从方法签名和超级调用中删除它,并通过self.request访问它。

1
2
3
4
def get_queryset(self, *args, **kwargs):
    qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
    qs = qs.filter(owner=self.request.user)
    return qs


get_queryset只需要self作为参数。

只需移除其他参数。