r/FastAPI • • Dec 27 '21

Question (HELP) 'Pydantic model' object is not subscriptable

Hey!

I'm trying to create an API where I take an array in a request body and then update a database based on the array values. I'm seeing the error in title and have no idea where it's going wrong.

This is my (part of my) code, and this is where the error happens.

@assessments.put("/qna/sort_order",
                 tags=["Assessments"])
async def update_assessments_sort_order(
        assessment_qna_sort_order: List[AssessmentQNASortOrder]):
    # loop through assessment_qna_sort_order and update sort_order
    for assessment_qna in assessment_qna_sort_order:
        sort_order = assessment_qna['sort_order']

The error occurs in the last line where I assign sort order. The AssessmentQNASortOrder pydantic model is:

class AssessmentQNASortOrder(BaseModel):
    assessment_qna_id: str
    sort_order: str

And the error I'm getting:

TypeError: 'AssessmentQNASortOrder' object is not subscriptable

I do not know what I'm doing wrong. My request body looks something like this:

[
{"sort_order": "1234", 
"user_id": 1},
{"sort_order": "12", 
"user_id": 2},
]

and printing assessment_qna_sort_order on the terminal gives me something like this, of type List

[AssessmentQNASortOrder(sort_order='1234', user_id='1'), AssessmentQNASortOrder(sort_order='12', user_id='2'), ]


<class 'list'>

Should i not be able to access the content of each index of the list using the bracket notation ['sort_order'] or ['user_id'] as I have done above?

Please help me out, thanks in advance!

1 Upvotes

1 comment sorted by

7

u/pint Dec 27 '21

fastapi converts the inputs to the types you've defined. in this case, AssessmentQNASortOrder. class members are accessed with the dot notation:

assessment_qna.sort_order