Comments (1)
I solved my problem and the solution can be divided into two options:
- Manually convert the sqlalchemy model to pydantic using the model inherited from BaseModel and its model_validate method
async def get_users(self) -> OffsetPagination[PydanticUser]:
results, count = await self.list_and_count()
results = [PydanticUser.model_validate(user, from_attributes=True) for user in results]
return self.to_schema(data=results, total=count, schema_type=PydanticUser)
- Manually convert sqlalchemy model to pydantic using TypaAdapter and its validate_python method
async def get_users(self) -> OffsetPagination[PydanticUser]:
results, count = await self.list_and_count()
# first option
results = TypeAdapter(list[PydanticUser]).validate_python(
results, from_attributes=True
)
# second option
# results = [TypeAdapter(PydanticUser).validate_python(user, from_attributes=True) for user in results]
return self.to_schema(data=results, total=count, schema_type=PydanticUser)
Important: It is necessary to specify the parameter `from_attributes=True' in the validation methods so that our DTO directly extracts data from the attributes and tries to substitute them
Alternatively, you can add the model_config attribute to your base model as follows:
class PydanticDefaultModel(BaseModel):
model_config = ConfigDict(
from_attributes=True,
)
class PydanticBaseUser(PydanticDefaultModel):
email: Optional[EmailStr] = None
is_active: Optional[bool] = True
is_superuser: bool = False
is_activated: bool = False
class PydanticUser(PydanticBaseUser):
id: int
async def get_users(self) -> OffsetPagination[PydanticUser]:
results, count = await self.list_and_count()
return self.to_schema(data=results, total=count, schema_type=PydanticUser)
Thanks to @cofin for the last solution 🦋
from litestar.
Related Issues (20)
- Bug: OpenAPI docs fail to generate with certain validators and pydantic v1 HOT 3
- Bug: Multi-body response incompatible with LoggingMiddleware HOT 2
- Bug: test failures
- Bug: `return_dto` is silently ignored if return data type does not match DTO definition HOT 1
- Bug: Test error
- Enhancement: add `default_json_serializer` to `__all__` in `litestar.logging.config`
- Docs: Migrating to Litestar from Django HOT 1
- Decoupled, transactional communication of domain events and commands
- Docs: Support for domain driven designs
- Enhancement: Repository pattern interfaces HOT 1
- Enhancement: Kubernetes application health endpoints HOT 1
- Enhancement: Allow status code categories in route handlers responses
- Enhancement: Provide option to set DTOs for nested fields HOT 7
- Bug: mounted app path interferes with regular paths HOT 4
- Examples not shown when using DTO HOT 1
- Bug: LoggingMiddleware breaks static file serving
- Bug: Redirect is not allowed for a preflight request. HOT 1
- Bug: Enum OAS issues HOT 1
- Enhancement: email service provider integration HOT 3
- Enhancement: Context Managers as Dependencies
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from litestar.