Declare indexes while keeping Pydantic and SQLModel logic separated #1001
Answered
by
ixycoexzckwpmlcu
choucavalier
asked this question in
Questions
Example Codefrom typing import Optional
from sqlmodel import Field as SQLField
from sqlmodel import SQLModel
from pydantic import BaseModel
class MyType(BaseModel):
some_attr: Optional[str] = None
some_other_attr: int = None
class MyTypeSQL(MyTypeBase, SQLModel, table=True):
id: Optional[int] = SQLField(default=None, primary_key=True)DescriptionHow can I declare |
Answered by
ixycoexzckwpmlcu
Jul 9, 2024
Replies: 1 comment
|
Just curious - why would you like to separate your Pydantic logic and SQLModel logic? Non-table SQLModel classes (i.e., without Adapted to your example, this would look like the following: from typing import Optional
from sqlmodel import Field, SQLModel
class MyType(SQLModel):
some_attr: Optional[str] = Field(index=True)
some_other_attr: int = None
class MyTypeSQL(MyType, table=True):
id: Optional[int] = Field(default=None, primary_key=True)If using SQLite (for example), this code would create the following table: CREATE TABLE mytypesql (
some_attr VARCHAR,
some_other_attr INTEGER NOT NULL,
id INTEGER NOT NULL,
PRIMARY KEY (id)
);
CREATE INDEX ix_mytypesql_some_attr ON mytypesql (some_attr); |
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just curious - why would you like to separate your Pydantic logic and SQLModel logic? Non-table SQLModel classes (i.e., without
table=true) won't create tables and will effectively function as Pydantic models (more in the FastAPI and Pydantic Tutorial, in particular the Multiple Models tutorial).Adapted to your example, this would look like the following:
If using SQLite (for example), this code would create the fol…