模型序列化器销毁方法

Model Serializer destroy method

我有一个名为 Profile 的模型,它是 Django 的 User 模型的包装器。现在,我通过以下方式创建了一个 ProfileSerializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = User.objects.create_user(**user_data, username=validated_data.get('username'))
        profile = Profile.objects.create(user=user, **validated_data)
        return profile
    
    def update(self, instance, validated_data):
        instance.dob = validated_data.get('dob', instance.dob)
        instance.karma = validated_data.get('karma', instance.karma)
        instance.username = validated_data.get('username', instance.username)
        user_data = validated_data.pop('user')
        instance.user.first_name = user_data.get('first_name', instance.user.first_name)
        instance.user.last_name = user_data.get('last_name', instance.user.last_name)
        instance.user.email = user_data.get('email', instance.user.email)
        instance.user.username = instance.username
        new_password = user_data.get('password')
        if new_password:
            instance.user.set_password(new_password)
        instance.user.save()
        instance.save()
        return instance

    class Meta:
        model = Profile
        fields = '__all__'

这里的问题是,当我尝试 DELETE 个人资料时,个人资料被删除但用户仍然存在。当发出 DELETE 请求时,我还需要能够删除用户。

我尝试进行一些搜索,但找不到 destroydelete ModelSerializer 的方法。

您可以使用 perform_destroy 方法在视图级别执行此操作:

class DetailProfile(RetrieveUpdateDestroyAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'username'
    lookup_url_kwarg = 'username'

    def perform_destroy(self, instance):
        user = instance.user
        instance.delete()
        user.delete()