In qgis 3, postgis, no DEM and zero python knowledge. I've got linestring 3d but Z coordinates is empty, Z-values are stored in table. Z1 for the first node, Z2 for the last node. I found a lot of ways to extract Z to populate the table but never opposite. I try "set Z value" processing, but I can't assign value Z1 to first point and Z2 to last point. I turn around with start_point, end_point,st_z, maybe st_makeline and others but I can't do it.
In case your lines are two vertice segments, this simply translates into
UPDATE <table> SET geom = ST_SetSRID( ST_MakeLine( ST_MakePoint( ST_X(ST_StartPoint(geom)), ST_Y(ST_StartPoint(geom)), "Z1":: FLOAT ), ST_MakePoint( ST_X(ST_EndPoint(geom)), ST_Y(ST_EndPoint(geom)), "Z2":: FLOAT ) ), <SRID> ) ;
Verbosely written for reference.
In case your LineStrings are polylines (with >2 vertices), this is a lot more involved.