Skip to content

Commit f7b771a

Browse files
author
Steven Chen
committed
one to many orm
1 parent db36ba3 commit f7b771a

3 files changed

Lines changed: 76 additions & 0 deletions

File tree

10_one_to_many_orm/__init__.py

Whitespace-only changes.

10_one_to_many_orm/db_init.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import datetime
2+
3+
from sqlalchemy import create_engine, String, ForeignKey
4+
from sqlalchemy.ext.declarative import declarative_base
5+
from sqlalchemy.orm import sessionmaker, Mapped, mapped_column, relationship
6+
from typing_extensions import Annotated
7+
from typing import List
8+
9+
10+
engine = create_engine('mysql://root:test@localhost/testdb', echo=True)
11+
Base = declarative_base()
12+
13+
14+
int_pk = Annotated[int, mapped_column(primary_key=True)]
15+
required_unique_name = Annotated[str, mapped_column(String(128), unique=True, nullable=False)]
16+
timestamp_not_null = Annotated[datetime.datetime, mapped_column(nullable=False)]
17+
18+
19+
class Department(Base):
20+
__tablename__ = "department"
21+
22+
id: Mapped[int_pk]
23+
name: Mapped[required_unique_name]
24+
25+
employees: Mapped[List["Employee"]] = relationship(back_populates="department")
26+
27+
def __repr__(self):
28+
return f'id: {self.id}, name: {self.name}'
29+
30+
31+
class Employee(Base):
32+
__tablename__ = "employee"
33+
34+
id: Mapped[int_pk]
35+
dep_id: Mapped[int] = mapped_column(ForeignKey("department.id"))
36+
name: Mapped[required_unique_name]
37+
birthday: Mapped[timestamp_not_null]
38+
39+
department: Mapped[Department] = relationship(lazy=False, back_populates="employees")
40+
41+
def __repr__(self):
42+
return f'id: {self.id}, dep_id: {self.dep_id}, name: {self.name}, birthday: {self.birthday}'
43+
44+
45+
Base.metadata.create_all(engine)
46+
Session = sessionmaker(bind=engine)

10_one_to_many_orm/query.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from db_init import Session, Department, Employee
2+
3+
4+
def insert_records(session):
5+
d1 = Department(name="hr")
6+
e1 = Employee(department=d1, name="Jack", birthday="2000-10-1")
7+
session.add(e1)
8+
9+
session.commit()
10+
11+
12+
def select_employee(session):
13+
emp = session.query(Employee).filter(Employee.id == 1).one()
14+
15+
print(emp)
16+
print(emp.department)
17+
18+
19+
def select_department(session):
20+
dep = session.query(Department).filter(Department.id == 1).one()
21+
22+
print(dep)
23+
print(dep.employees)
24+
25+
26+
session = Session()
27+
28+
# insert_records(session)
29+
# select_employee(session)
30+
select_department(session)

0 commit comments

Comments
 (0)