Add default values to optional fields in SampleUpdate

This commit is contained in:
GotthardG
2025-01-09 22:51:26 +01:00
parent ac38bc3bb6
commit 0f6759e417
4 changed files with 213 additions and 64 deletions

View File

@ -313,6 +313,40 @@ async def download_dewar_label(dewar_id: int, db: Session = Depends(get_db)):
)
@router.put("/samples/{sample_id}", response_model=Sample)
async def update_sample(
sample_id: int,
sample_update: SampleUpdate,
db: Session = Depends(get_db),
):
# Log the payload received from the frontend
logging.info(
f"Payload received for sample ID {sample_id}: "
f"{sample_update.dict(exclude_unset=True)}"
)
# Query the sample from the database
sample = db.query(SampleModel).filter(SampleModel.id == sample_id).first()
if not sample:
logging.error(f"Sample with ID {sample_id} not found")
raise HTTPException(status_code=404, detail="Sample not found")
# Apply updates
for key, value in sample_update.dict(exclude_unset=True).items():
if hasattr(sample, key):
setattr(sample, key, value)
# Commit changes to the database
db.commit()
db.refresh(sample) # Reload the updated sample object
# Log the updated sample before returning it
logging.info(f"Updated sample with ID {sample_id}: {Sample.from_orm(sample)}")
return Sample.from_orm(sample)
@router.get("/dewars/{dewar_id}/samples", response_model=Dewar)
async def get_dewar_samples(dewar_id: int, db: Session = Depends(get_db)):
# Fetch the Dewar with nested relationships
@ -374,27 +408,6 @@ async def get_dewar_samples(dewar_id: int, db: Session = Depends(get_db)):
return Dewar(**dewar_data)
@router.put("/samples/{sample_id}", response_model=Sample)
async def update_sample(
sample_id: int,
sample_update: SampleUpdate,
db: Session = Depends(get_db),
):
sample = db.query(SampleModel).filter(SampleModel.id == sample_id).first()
if not sample:
raise HTTPException(status_code=404, detail="Sample not found")
# Apply updates
for key, value in sample_update.dict(exclude_unset=True).items():
if hasattr(sample, key):
setattr(sample, key, value)
# Save changes
db.commit()
db.refresh(sample)
return Sample.from_orm(sample)
@router.get("/", response_model=List[DewarSchema])
async def get_dewars(db: Session = Depends(get_db)):
try:

View File

@ -619,12 +619,12 @@ class SlotSchema(BaseModel):
class SampleUpdate(BaseModel):
sample_name: Optional[str]
proteinname: Optional[str]
priority: Optional[int]
position: Optional[int]
comments: Optional[str]
data_collection_parameters: Optional[DataCollectionParameters]
sample_name: Optional[str] = None
proteinname: Optional[str] = None
priority: Optional[int] = None
position: Optional[int] = None
comments: Optional[str] = None
data_collection_parameters: Optional[DataCollectionParameters] = None
class Config:
from_attributes = True