Trying to return form data in a nested list. Current code returns the below format:
{
"name":"meal number 4",
"description":"new description",
"ing_qty":"4",
"ing_type":"small",
"ing_name":"Tomato",
"ing_id":"9"
}
Printing raw FormData results in:
FormData([('name', 'meal number 4'), ('description', 'new description'), ('ing_qty', '4'), ('ing_type', 'small'), ('ing_name', 'Onion'), ('ing_id', '6'), ('ing_qty', '4'), ('ing_type', 'small'), ('ing_name' , 'Red'), ('ing_id', '7'), ('ing_qty', '4'), ('ing_type', 'small'), ('ing_name', 'Tomato'), ('ing_id', '8'), ('ing_qty', '4'), ('ing_type', 'small'), ('ing_name', 'Tomato'), ('ing_id', '9')])
I am trying to get the results into the below format so that i may update my db recrds with the form data.
{
"name":"string",
"description":"string",
"ingredients":[
{
"ing_id":null,
"ing_qty":null,
"ing_type":null,
"ing_name":null
}
]
}
Here are my Pydantic BaseModels
class IngUpdate(BaseModel):
ing_id: Optional[int]
ing_qty: Optional[int]
ing_type: Optional[str]
ing_name: Optional[str]
class RecipeUpdate(BaseModel):
name: Optional[str]
description: Optional[str]
ingredients: List[IngUpdate] = []
Here is my Post Request:
@router.post("/edit/{recipe_id}")
async def edit_select_recipe(request: Request, recipe_id: int,
db: Session = Depends(get_db)):
data = await request.form()
print(data)
return data
Adding Response Model to Post returns the following result:
{
"name":"meal number 4",
"description":"new description",
"ingredients":[
]
}
It appears it's unable to pull the data into a list. How can I get this into a nest model?
ing_id: Optional[List[int]] = Form(),ing_qty: Optional[List[str]] = Form(), etc., then convert this to the format you want to submit to your db/service layer.