OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to validate SQLAlchemy session.execute(stmt).scalars().all() result using by Pydantic model

  • Thread starter Thread starter Сергей Севастьянов
  • Start date Start date
С

Сергей Севастьянов

Guest
Code:
@router.get("/get_in_list/", status_code=status.HTTP_200_OK, response_model=LanguageModelResponse)
async def get_language_list(
    label: Optional[str],
    session: AsyncSession = Depends(get_db),
) -> List[LanguageModelResponse]:
    
    """
    Получение списка языков(фильтр по label)

    """
    stmt = select(LanguageModel)

    if label is not None:
        stmt = stmt.where(LanguageModel.label.ilike(f"%{label}%"))

    query =  (await session.execute(stmt)).scalars().all()
    print('asdasd', type(query))

    return [LanguageModelResponse.model_validate(row) for row in query]

When i try validate query im getting error: {'type': 'model_attributes_type', 'loc': ('response',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': [LanguageModelResponse(id=329135526940508160, label='Yakut', code='ykt'), LanguageModelResponse(id=329135526940508161, label='Turkish', code='trk')], 'url': 'https://errors.pydantic.dev/2.3/v/model_attributes_type'} Solution it is to convert query result to dict but i dont know how to do this

Im already tried mapping().all() methods
<pre><code>@router.get("/get_in_list/", status_code=status.HTTP_200_OK, response_model=LanguageModelResponse)
async def get_language_list(
label: Optional[str],
session: AsyncSession = Depends(get_db),
) -> List[LanguageModelResponse]:

"""
Получение списка языков(фильтр по label)

"""
stmt = select(LanguageModel)

if label is not None:
stmt = stmt.where(LanguageModel.label.ilike(f"%{label}%"))

query = (await session.execute(stmt)).scalars().all()
print('asdasd', type(query))

return [LanguageModelResponse.model_validate(row) for row in query]
</code></pre>
<p>When i try validate query im getting error: <code>{'type': 'model_attributes_type', 'loc': ('response',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': [LanguageModelResponse(id=329135526940508160, label='Yakut', code='ykt'), LanguageModelResponse(id=329135526940508161, label='Turkish', code='trk')], 'url': 'https://errors.pydantic.dev/2.3/v/model_attributes_type'}</code>
Solution it is to convert query result to dict but i dont know how to do this</p>
<p>Im already tried <code>mapping().all()</code> methods</p>
 
Top