[Answer]-Create new related object when updating one

1πŸ‘

βœ…

In Django REST Framework 3.0, serializers must explicitly handle nested updates, which is essentially what you are trying to do here. You would just need to override perform_update and have it create the new Weight object instead of manually updating it.

In Django REST Framework 2.4, much of this happens automagically, and you are trying to change that magic behavior.

Django will do an update on a model object if the object has an id on it, and an update if id is set to None. This means that you can create a basic copy of the object by setting the id to None, which is the easiest way to do what you are looking for right now.

class UserDetails(APIView):
    def post(self, request, format=None):
        user = request.user
        if user.is_authenticated():
            serializer = UserSerializer(user, data=request.DATA, partial=True)
            if serializer.is_valid():
                user.weight.pk = None
                user.weight.save()
                serializer.save()
                return Response(serializer.data)

This should cause a new Weight object to be created each time the user is updated.

Leave a comment