How to convert a sqlmodel class to pydantic class #850
Replies: 3 comments 1 reply
-
To just create: heroplus = HeroPlus.model_validate(hero_deadpond.model_dump()) And to add something: deadpond_dump = hero_deadpond.model_dump()
deadpond_dump['fans'] = fans_from_other_source
heroplus = HeroPlus.model_validate(deadpond_dump) I've been doing things like this, not related to SQLModel though but otherwise with Pydantic 2. Am curious to know if there's a better way but I guess that's ok. Oh there's also this way that I'm using in some places, which is a tad nicer, forgot about it first: heroplus = HeroPlus(
fans = fans_from_other_source
**hero_deadpond.model_dump()
) I made a replit where this works with a simplified version, https://replit.com/@antont3/Pydantic-object-from-another#main.py The code there is: from pydantic import BaseModel
class Hero(BaseModel):
name: str
age: int
class HeroPlus(Hero):
fans: list[str] # property from other sources
hero = Hero(name="Batman", age=42)
fans_from_other_source = ["Superman", "Wonder Woman"]
hero_plus = HeroPlus(
fans=fans_from_other_source,
**hero.model_dump()
)
print(hero_plus) Outputs:
|
Beta Was this translation helpful? Give feedback.
-
It works in very simple cases, but the wired problem is I have to create a model in So I can not create a pydantic base model and inherit it. |
Beta Was this translation helpful? Give feedback.
-
I create a stupid function to transfer sqlmodel to pydantic
There should be some better inherit method |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I plan to use
HeroPlus
schema to add some information from other sources to hero , e.g. a request.But I can not find a way to create a pydantic model from sqlmodel.
Operating System
Linux, Windows
Operating System Details
No response
SQLModel Version
0.0.16
Python Version
Python 3.10.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions