Modelviewset删除方法覆盖

时间:2020-05-19 16:31:49

标签: django django-rest-framework

我有用户视图,当我尝试删除用户时,我想删除使用相同电子邮件的邀请模型。 如何使用销毁方法删除具有相同电子邮件的用户{id}和邀请模型{id)。

我的模型:

class User(AbstractBaseUser):
    first_name = models.CharField(max_length=254)
    last_name = models.CharField(max_length=254)
    email = models.EmailField(unique=True)

class Invite(models.Model):
    email = models.EmailField(unique=True)

我的视图集:

class ActiveUserView(ModelViewSet):
    queryset = User.objects.all()
    permission_classes = [IsAuthenticated]
    http_method_names = ['get', 'delete']
    serializer_class = SomeUserSerializer

    def destroy(self, request, *args, **kwargs):
        user = request.user
        for user in users:
            Invite.objects.filter(email=user.email)
            invite = Invite.objects.get(email=user.email)
            invite.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

1 个答案:

答案 0 :(得分:1)

这里不需要for循环,首先从get_object()方法中获取对象,然后删除Invite对象。

    def destroy(self, request, *args, **kwargs):
        user_object = self.get_object()
        Invite.objects.filter(email=user_object.email).delete()
        user_object.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)