mirror of
https://github.com/fastapi/sqlmodel.git
synced 2025-08-14 17:41:37 +08:00
✨ Document indexes and make them opt-in (#205)
This commit is contained in:

committed by
GitHub

parent
3d7b74746c
commit
155c6178cd
51
docs_src/tutorial/indexes/tutorial001.py
Normal file
51
docs_src/tutorial/indexes/tutorial001.py
Normal file
@ -0,0 +1,51 @@
|
||||
from 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)
|
||||
|
||||
|
||||
sqlite_file_name = "database.db"
|
||||
sqlite_url = f"sqlite:///{sqlite_file_name}"
|
||||
|
||||
engine = create_engine(sqlite_url, echo=True)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
def create_heroes():
|
||||
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
|
||||
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
|
||||
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
|
||||
|
||||
with Session(engine) as session:
|
||||
session.add(hero_1)
|
||||
session.add(hero_2)
|
||||
session.add(hero_3)
|
||||
|
||||
session.commit()
|
||||
|
||||
|
||||
def select_heroes():
|
||||
with Session(engine) as session:
|
||||
statement = select(Hero).where(Hero.name == "Deadpond")
|
||||
results = session.exec(statement)
|
||||
for hero in results:
|
||||
print(hero)
|
||||
|
||||
|
||||
def main():
|
||||
create_db_and_tables()
|
||||
create_heroes()
|
||||
select_heroes()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Reference in New Issue
Block a user