Django rest Framework-需要项目列表,但类型为“ QuerySet”

时间:2019-10-20 08:33:12

标签: django django-serializer

我尝试序列化查询集。但是我得到了 {'non_field_errors':[ErrorDetail(string ='Expected a items of list but but type type“ QuerySet”。',code ='not_a_list')]} 错误。如何解决这个错误。

    def post(self, request):
        data = request.data
        user_name = data.get('username')
        signup_filtered_data = Signup.objects.filter(username= user_name).values()
        print(signup_filtered_data)
        serializer = SignupSerializer(data= signup_filtered_data, many=True)
        serializer.is_valid()
        print(serializer.errors)
        signup_jason_data = json.dumps(serializer.data)
        return HttpResponse(signup_jason_data)

models.py

class Signup(models.Model):
    first_name = models.CharField(max_length=50, blank=True, null=True)
    last_name = models.CharField(max_length=50, blank=True, null=True)
    email = models.EmailField(max_length=50, unique= True)
    phone_number = models.CharField(max_length=12, unique= True)
    username = models.CharField(max_length=50, unique= True)
    password = models.CharField(max_length=50, blank=True, null=True)

serializers.py

class SignupSerializer(serializers.ModelSerializer):

    class Meta:
        model = Signup
        fields = '__all__'

2 个答案:

答案 0 :(得分:1)

当您将数据传递给序列化程序时,您在视图中使用了many = True,但实际上您只发送了一条消息。

def post(self, request, formate = None):
   serializer = SignupSerializer(data= signup_filtered_data)

查看实际答案: Actual answer

答案 1 :(得分:1)

一种更简洁的方法是使用基于类的视图的过滤器和序列化器 一个例子是使用mixins

Mixins DjangoRest

FilterBackend DjangoRest

Pagination DjangoRest

Permissions Classes DjangoRest

filters.py

class SignupFilter(django_filters.FilterSet):

    class Meta:
        model = Signup
        fields = [
            'user_name',
        ]

views.py

class YourNameView(mixins.CreateModelMixin,
                   viewsets.GenericViewSet):

    permission_classes = [permissions.IsAuthenticated, ] # Permission Classes
    pagination_class = PageNumberPagination # Pagination Classes
    serializer_class = SignupSerializer # Your Serializer
    filter_backends = [DjangoFilterBackend] #This need to added on settings.py
    filter_class = SignupFilter # Your filter Class
    queryset = Signup.objects.all() 

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)