4

When I use the Django Rest Framework to delete a User, the associated UserProfile object also gets deleted. I would like for the reverse relationship to also be true. How can I do this?

I have a Django model that represents a User's profile.

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

Here are my Views:

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

And the serializers:

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')

1 Answer 1

2

You could overwrite the delete method at your UserProfile class, like this:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.