如何在Django rest Framework中执行Delete操作?

时间:2018-07-23 15:00:43

标签: django django-rest-framework

您好,我是Django rest框架中的新手,我想创建自定义删除功能以删除。我成功创建了 create update ,如下面的代码所示,但是我无法创建删除功能。但是我搜索了很多有关此功能的文章,但没有找到。希望您能帮到我。

1。 models.py

   class User(AbstractUser, BaseModel):


    full_name = models.CharField(max_length=64)

        addresss=models.CharField(max_length=40)

        phoneno=models.IntegerField(null=True, blank=True)

        email=models.EmailField()

        password=models.CharField(max_length=40)

        re_password=models.CharField(max_length=40)


        gender=models.IntegerField(choices=gender_choice,default='0')

    ##models for student register
    class Student(BaseModel):
        user = models.ForeignKey(User, on_delete=models.CASCADE)

        father_name=models.CharField(max_length=64)
        mother_name=models.CharField(max_length=60)
        date_of_birth=models.DateField(null=True)

        def __str__(self):
            return self.user.full_name

2。 Serializer.py

    class StudentSerializer(serializers.HyperlinkedModelSerializer):
        user = UserSerializer()
        class Meta:
            model=Student
            fields=(
                'id',
                'father_name',
                'mother_name',
                'date_of_birth',
                'user',
                )

 3. serializer.for user

    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = User
            fields=('full_name','id','addresss','phoneno','email','password','re_password','gender')

4。 views.py

    class StudentViewset(viewsets.ModelViewSet):
        queryset = Student.objects.all()
        serializer_class = StudentSerializer

        http_methods = ['get', 'post','put',]


        def create(self, request):
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)

            row = serializer.data
            user = row['user']

            if user['password'] != user['re_password']:
                return Response({'message':'pw not matched'})

            email = username = row['user']['email']

            user, created = User.objects.get_or_create(email=email, 
                defaults={'full_name':row['user']['full_name'],'addresss':row['user']['addresss'],
                'phoneno':row['user']['phoneno'],'password':row['user']['password'] ,'re_password':row['user']['re_password'],
                'gender':row['user']['gender'] ,'username':username})

            if created == False:
                return Response({'message':'Sorry the student is already registered.'})

            student = Student.objects.create(user_id=user.id)

            return Response(row)

        def update(self,request,*args,**kwargs):
            instance=self.get_object()
            serializer=StudentUpdateSerializer(data=request.data)

            serializer.is_valid(raise_exception=True)

            data = serializer.data
            if data.get('father_name', False):
                instance.father_name = data.get('father_name')

            if data.get('mother_name', False):
                instance.mother_name = data.get('mother_name')

            instance.save()
            return Response(serializer.data)
Q.
def delete(..)#How to write this delete Function???

2 个答案:

答案 0 :(得分:1)

ModelViewSet具有一个在您执行DELETE请求时调用的函数,它称为destroy

它是这样的:

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

因此要从数据库中删除实例,可以执行

instance.delete()

这实际上是perform_destroy的作用。

因此您可以从中获得启发并实施自定义删除。

答案 1 :(得分:0)

还有一个基于通用删除类的视图,如here