python - 使用 Django Rest Framework API 删除相关模型

标签 python django django-rest-framework

当我使用 Django Rest Framework 删除用户时,关联的 UserProfile 对象也会被删除。我希望反向关系也成立。我该怎么做?

我有一个代表用户个人资料的 Django 模型。

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    preferred_name = models.CharField(max_lengths=100)
    #other fields here

这是我的观点:

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    """ 
    API endpoint that represents a single user.
    """
    model = User
    serializer_class = UserSerializer

class UserProfileDetail(generics.RetrieveUpdateDestroyAPIView):
    """ 
    API endpoint that represents a single UserProfile
    """
    model = UserProfile
    serializer_class = UserProfileSerializer

还有序列化器:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    profile = serializers.HyperlinkedRelatedField(view_name = 'userprofile-detail')

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'profile')

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = UserProfile
        fields = ('url', 'preferred_name', 'user')

最佳答案

您可以覆盖 UserProfile 类中的 delete 方法,如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    preferred_name = models.CharField(max_lengths=100)
    #other fields here
    def delete(self, *args, **kwargs):
        self.user.delete()
        super(UserProfile, self).delete(*args, **kwargs)

关于python - 使用 Django Rest Framework API 删除相关模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592764/

相关文章:

在 postgresql 中迁移模型时 postgresql TypeError 上的 django-cms 迁移问题

python - 如何在 DRF 中访问 ListSerializer 父类的 serializer.data?

django - 在 Django Rest Framework 中使用 HyperlinkedField 进行序列化器

python - 密码重置功能 Django-Registration-Redux 应用程序

python - 来自 stdin 用例的脚本

python - 在 Windows 的 VirtualEnv 中安装 Numpy

python - 更改 matplotlib.pyplot 点的颜色

javascript - 如何将日期/日历小部件添加到 django 表单?

python - 每当获取任何实体时添加计数 Django REST Framework

python - 从组合列表中选择对的最佳策略