Declare indexes while keeping Pydantic and SQLModel logic separated #1001
-
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 |
Beta Was this translation helpful? Give feedback.
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); |
Beta Was this translation helpful? Give feedback.
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…