forked from disouzam/sql-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorm_relation.py
More file actions
28 lines (22 loc) · 803 Bytes
/
orm_relation.py
File metadata and controls
28 lines (22 loc) · 803 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from sqlmodel import Field, Session, SQLModel, create_engine, select
import sys
from typing import Optional
class Department(SQLModel, table=True):
ident: str = Field(default=None, primary_key=True)
name: str
building: str
# [keep]
class Staff(SQLModel, table=True):
ident: str = Field(default=None, primary_key=True)
personal: str
family: str
dept: Optional[str] = Field(default=None, foreign_key="department.ident")
age: int
db_uri = f"sqlite:///{sys.argv[1]}"
engine = create_engine(db_uri)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
statement = select(Department, Staff).where(Staff.dept == Department.ident)
for dept, staff in session.exec(statement):
print(f"{dept.name}: {staff.personal} {staff.family}")
# [/keep]