4

当我使用 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')
4

1 回答 1

2

您可以在 UserProfile 类中覆盖删除方法,如下所示:

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)
于 2013-06-01T17:23:42.093 回答