[Fixed]-HyperlinkedRelatedField not working with to_internal_value (Django Rest Framework)


You cannot do this:

def to_internal_value(self, data):
    return data

Serializer.to_internal_value validates the received data (data) and converts it into types that are useful on the ORM level.

For HyperLinkedRelatedFields it retrieves (via HyperLinkedRelatedField.to_internal_value) the object that is being linked to. In your case, you directly passed unvalidated data which contained the URLs instead of objects. This might have worked if data contained only primitive types, but would still be insecure.

If you are about to do any transformations, retrieve the objects first:

def to_internal_value(self, data):
    validated_data = super().to_internal_value(data)
    # Your transformations on validated_data
    return validated_data

Leave a comment