python SQLAchemy多外键关联
时间:2021-07-01 10:21:17
帮助过:29人阅读
from sqlalchemy
import Integer, ForeignKey, String, Column
2 from sqlalchemy.ext.declarative
import declarative_base
3 from sqlalchemy.orm
import relationship
4 from sqlalchemy
import create_engine
5 Base =
declarative_base()
6
7
8 class Customer(Base):
9 __tablename__ =
‘customer‘
10 id = Column(Integer, primary_key=
True)
11 name = Column(String(64
))
12
13 billing_address_id = Column(Integer, ForeignKey(
"address.id"))
14 shipping_address_id = Column(Integer, ForeignKey(
"address.id"))
15
16 billing_address = relationship(
"Address",foreign_keys=
[billing_address_id])
17 shipping_address = relationship(
"Address",foreign_keys=
[shipping_address_id])
18
19
20 class Address(Base):
21 __tablename__ =
‘address‘
22 id = Column(Integer, primary_key=
True)
23 street = Column(String(64
))
24 city = Column(String(64
))
25 state = Column(String(64
))
26
27 def __repr__(self):
28 return self.street
29
30 engine = create_engine(
"mysql+pymysql://root:@localhost/test",encoding=
‘utf-8‘)
31 Base.metadata.create_all(engine)
# 创建表结构
orm_api.py 添加数据。查询
python SQLAchemy多外键关联
标签:ons 表结构 ati pytho ddr local self _id table