How to build/output a model like FastAPI does with response_model #794
-
First Check
Commit to Help
Example Codefrom typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True) DescriptionSo, I build a generic model which imports from SQLModel. I've traced SQLModel back and it inherits Pydantic's BaseModel. Perfect. From there, I'm attempting to output (to OUTPUT, to UI, to anything - doesn't matter) the class back to the user much like is done in FastAPI's schema. For example, the FastAPI page would show: Schemas Or something like that. How is this achieved? I thought I could just use jsonable_encoder on Hero, but it gives me the fields with what they're filled with (which makes sense) - e.g., None with an empty model. So, then I thought I could rip through the model's fields and use SQLModel's get_sqlalchemy_type, but I can't access it from Hero since this method is outside of the SQLModel class (though in the SQLModel module). Any thoughts on the proper way to convert my Hero into JSON (or whatever) that provides the name of the field and it's type? I can just create my own, but I'm assuming there's a built-in that already does this. Thank you! Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.103.1 Python Version3.11.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
@blackhillsystems , I'm not 100% sure I understand what you are asking. Does |
Beta Was this translation helpful? Give feedback.
-
How did I miss that!?!?!? That'll work perfectly! Thank you @riziles ! |
Beta Was this translation helpful? Give feedback.
@blackhillsystems , I'm not 100% sure I understand what you are asking. Does
Hero.schema()
orHero.schema_json()
give you what you are looking for?