0

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?

3
  • Your question is a bit hard to read (please fomat the JSON to be readable and clarify what it is you want) but it seems like you're not using you're Pydantic models? Commented Feb 12, 2023 at 9:31
  • 1
    Plain form data doesn't have a nested structure - if you want to get a nested structure directly from a POST, use a JSON body instead of plain form data - or create a flat structure that you transform into the one you want (with 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. Commented Feb 12, 2023 at 20:28
  • Related (opposite problem): stackoverflow.com/q/75289130/19770795 Commented Feb 13, 2023 at 9:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.