Django rest-framework,序列化器返回Assert错误

8yparm6h  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(109)

我正在扩展我当前的模型,使其具有一些来自其他基类的公共属性。在扩展模型之前,一切都工作正常。但是在扩展之后,我在执行put和post操作时遇到了Assert错误。我尽了最大努力自己解决它。但是没有找到错误的地方。有人能帮助我吗?请在下面找到我的模型和序列化程序。
basemodel.py

from django.db import models

class BaseModel(models.Model):
    created_at=models.DateTimeField(auto_now=True)
    updated_at=models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

softdelete.py

from django.db import models

class SoftDeleteModel(models.Model):
    is_deleted = models.BooleanField(default=False)

    def delete(self):
        self.is_deleted = True
        self.save()

    def restore(self):
        self.is_deleted = False
        self.save()

    class Meta:
        abstract = True

movies.py

from django.db import models
from cinimateApp.models.comman.softdelete import SoftDeleteModel
from cinimateApp.models.comman.basemodel import BaseModel

# Create your models here.

class Movies(SoftDeleteModel,BaseModel):
    name=models.CharField(max_length=250)
    description=models.CharField(max_length=250)
    active=models.BooleanField(default=False)

    def __str__(self):
        return self.name

movieSerializer.py

#Model Serializer

from rest_framework import serializers
from cinimateApp.models.movies import Movies

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movies
        fields = '__all__' 
        # fields=['id', 'name', 'description', 'active']
        # exclude=['name']
    
    # field Level Validation
    def validate_name(self,value):
        if(len(value)<3):
            raise serializers.ValidationError('name is too short')
        return value

    #Objectlevel validation
    def validate(self,data):
        if(data['name']==data['description']):
            raise serializers.ValidationError('name and description should be different')
        return 

    #custome serializer field
    name_length=serializers.SerializerMethodField()
    def get_name_length(self,object):
        return len(object.name)

views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from cinimateApp.serializers.movieSerializer import MovieSerializer
from cinimateApp.models.movies import Movies

# Create your views here.

class MovieList(APIView):
    def get(self,request):
        movies=Movies.objects.all()
        serializer=MovieSerializer(movies,many=True)
        return Response(serializer.data,status=status.HTTP_200_OK)

    def post(self,request):
        serialiser=MovieSerializer(data=request.data)
        if(serialiser.is_valid()):
            serialiser.save()
            return Response(serialiser.data,status=status.HTTP_201_CREATED)
        else:
            return Response(serialiser.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class MovieDetailsAV(APIView):
    def get(self,request,id):
        try:
            movie=Movies.objects.get(pk=id)
            serializer=MovieSerializer(movie)
            return Response(serializer.data,status=status.HTTP_200_OK)
        except Movies.DoesNotExist:
            return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)

    def put(self,request,id):
        try:
            movie=Movies.objects.get(pk=id)
            serializer=MovieSerializer(movie,data=request.data)
            if(serializer.is_valid()):
                serializer.save()
                return Response(serializer.data,status=status.HTTP_200_OK)
            return Response(serializer.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Movies.DoesNotExist:
            return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)

    def delete(self,request,id):
        try:
            movie=Movies.objects.get(pk=id)
            movie.delete()
            return Response({'message' : 'Content deleted successfully'},status=status.HTTP_204_NO_CONTENT)
        except Movies.DoesNotExist:
            return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)

    def patch(self,request,id):
        try:
            movie=Movies.objects.get(pk=id)
            serializer=MovieSerializer(movie,data=request.data,partial=True)
            if(serializer.is_valid()):
                serializer.save()
                return Response(serializer.data,status=status.HTTP_200_OK)
            return Response(serializer.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Movies.DoesNotExist:
            return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)

对于put和post请求,我收到以下错误。assert值不是None,'。validate()应返回已验证的数据' AssertionError:.validate()应返回已验证的数据

piok6c0g

piok6c0g1#

validate()函数应返回数据,因此:

def validate(self,data):
        if(data['name']==data['description']):
            raise serializers.ValidationError('name and description should be different')
        return data

相关问题