@@ -220,25 +220,35 @@ async def update(session: SessionDep, editor: UserEditor, trans: Trans):
220220 if not check_email_format (editor .email ):
221221 raise Exception (trans ('i18n_format_invalid' , key = f"{ trans ('i18n_user.email' )} [{ editor .email } ]" ))
222222 origin_oid : int = user_model .oid
223- del_stmt = sqlmodel_delete (UserWsModel ).where (UserWsModel .uid == editor .id )
224- session .exec (del_stmt )
223+
224+ uws_list_stmt = select (UserWsModel ).where (UserWsModel .uid == editor .id )
225+ uws_list = session .exec (uws_list_stmt ).all ()
226+
227+ existing_oids = {uws .oid for uws in uws_list }
228+ new_oid_set = set (editor .oid_list ) if editor .oid_list else set ()
229+ oids_to_remove = existing_oids - new_oid_set
230+ oids_to_add = new_oid_set - existing_oids
231+
232+ if oids_to_remove :
233+ del_stmt = sqlmodel_delete (UserWsModel ).where (UserWsModel .uid == editor .id , UserWsModel .oid .in_ (oids_to_remove ))
234+ session .exec (del_stmt )
225235
226236 data = editor .model_dump (exclude_unset = True )
227237 user_model .sqlmodel_update (data )
228238
229239 user_model .oid = 0
230240 if editor .oid_list :
231- # need to validate oid_list
232- db_model_list = [
233- UserWsModel .model_validate ({
234- "oid" : oid ,
235- "uid" : user_model .id ,
236- "weight" : 0
237- })
238- for oid in editor .oid_list
239- ]
240- session .add_all (db_model_list )
241241 user_model .oid = origin_oid if origin_oid in editor .oid_list else editor .oid_list [0 ]
242+ if oids_to_add :
243+ db_uws_model_list = [
244+ UserWsModel .model_validate ({
245+ "oid" : oid ,
246+ "uid" : user_model .id ,
247+ "weight" : 0
248+ })
249+ for oid in oids_to_add
250+ ]
251+ session .add_all (db_uws_model_list )
242252 session .add (user_model )
243253
244254@router .delete ("/{id}" , summary = f"{ PLACEHOLDER_PREFIX } user_del_api" , description = f"{ PLACEHOLDER_PREFIX } user_del_api" )
0 commit comments