python SQLAchemy多外键关联
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python SQLAchemy多外键关联相关的知识,希望对你有一定的参考价值。
关联同一张表的两个字段
创建表结构
orm_many_fk.py 只创建表结构
1 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多外键关联的主要内容,如果未能解决你的问题,请参考以下文章