-
First Check
Commit to Help
Example CodeActualData(BaseModel):
id: int
KnownName: str
NickName: str
Mother: str
Father: str
SocialSecurity: int
Pets: Optional[boolean]
Vegan: Optional[boolean]
DescriptionI have a very strange constraint, I am using SQLModel as my orm. I have a database with two important fields, for example How do I use the pydantic/validators was very helpful but it fills one field. Is it possible to fill out the entire model with one validator? How does one encode the model back to a single string within the database? Operating SystemWindows Operating System Details
SQLModel Version0.0.8 Python Version3.10.8 Additional ContextThink of storing the string components of postgresql database connection string, but storing it as a completed connection string
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I recommend you use a JSON column for details. anyway, you have to create a new type: from sqlalchemy.types import TypeDecorator, String
class ActualDataType(TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
if value is not None:
value = ";".join(f"{k}={v}" for k, v in value.dict().items() if v is not None)
return value
def process_result_value(self, value, dialect):
if value is not None:
d = {}
for value in value.split(";"):
k, v = value.split("=")
d[k] = v
value = ActualData(**d)
return value for JSON: from sqlalchemy.types import TypeDecorato, JSON
class ActualDataType(TypeDecorator):
impl = JSON
def process_bind_param(self, value, dialect):
if value is not None:
value = value.dict()
return value
def process_result_value(self, value, dialect):
if value is not None:
value = ActualData(**value)
return value And finally, change the column type to be from sqlalchemy import Column
class Data(SQLModel, table=True):
...
details: ActualData = Field(sa_column=Column(ActualDataType)) |
Beta Was this translation helpful? Give feedback.
-
@meirdev you are amazing, thank you for your suggestion. I will try this out and report back. |
Beta Was this translation helpful? Give feedback.
I recommend you use a JSON column for details. anyway, you have to create a new type:
for JSON: