I have the following models:
from pydantic import BaseModel
class OrderModel(BaseModel):
id: int
title: str
class ConfigDict:
from_attributes = True
class ItemModel(BaseModel):
id: int
description: str
class ConfigDict:
from_attributes = True
class ResponseModel(BaseModel):
order: OrderModel
items: list[ItemModel]
And my objects are:
order = SqlAlchemySession.query(Order).first()
items = SqlAlchemtSession.query(Item).all()
I want to use ResponseModel to return data for users (in a FastAPI project). but I don't know how can I do that. I tested the following and it works. But I need a way that has better performance. I think For Loop is not fine for performance:
ResponseModel(
order=OrderModel(**order.__dict__),
items=[ItemModel(**item.__dict__) for item in items]
)
how can I do that without For Loop?
Is there any way to use as follows?
response_model = ResponseModel(order=order, items=items)
The solution is:
Example:
Output: