sqlalchemy外鍵的一些東西
阿新 • • 發佈:2018-11-22
eat HERE fir 聯表查詢 字段 self 數據庫 ada info
數據庫:
聯表查詢:
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,Integer from sqlalchemy.orm import sessionmaker engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest") Base = declarative_base() class Student(Base):__tablename__ = ‘student‘ id = Column(Integer, primary_key=True) name = Column(String(32)) sex = Column(String(32)) def __repr__(self): return "%s,%s,%s" %(self.id, self.name, self.sex) class Study_record(Base): __tablename__ = ‘study_record‘ id = Column(Integer, primary_key=True) day= Column(Integer) status = Column(String(32)) stu_id = Column(Integer) def __repr__(self): return "%s,%s,%s" %(self.day, self.status, self.stu_id) Session_class = sessionmaker(bind=engine) session = Session_class() # select a.*,b.* from a,b where a.id=b.s_id result = session.query(Student, Study_record).filter(Student.id==Study_record.stu_id).all()print(result) # [(1,alex,男, 1,YES,1), (1,alex,男, 2,NO,1), (2,jack,男, 1,YES,2), (2,jack,男, 2,YES,2)] # 此處報錯!!有外鍵關聯的時候才能用,而且外鍵也需要用類映射出來。真TM麻煩! result1 = session.query(Student).join(Study_record).all() print(result1)
外鍵關聯之雙向反查:
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,Integer from sqlalchemy.orm import sessionmaker,relationship from sqlalchemy import ForeignKey engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest") Base = declarative_base() # 學員表student跟考勤表study_record是一對多的關系 class Student(Base): __tablename__ = ‘student‘ id = Column(Integer, primary_key=True) name = Column(String(32)) sex = Column(String(32)) def __repr__(self): return "%s,%s,%s" %(self.id, self.name, self.sex) class Study_record(Base): __tablename__ = ‘study_record‘ id = Column(Integer, primary_key=True) day = Column(Integer) status = Column(String(32)) stu_id = Column(Integer, ForeignKey(‘student.id‘)) # 雙向反查關系,通過student字段可以看記錄對應的學生,反過來通過my_study_record可看學生對應的記錄 student = relationship("Student", backref="my_study_record") def __repr__(self): # self.student.name 這是它的牛逼之處: return "%s,%s,%s" %(self.day, self.status, self.student.name) Session_class = sessionmaker(bind=engine) session = Session_class() # 上面加了外鍵關聯,可以用了 result1 = session.query(Student).join(Study_record, isouter=True).all() print(result1) # [1,alex,男, 2,jack,男, 3,rose,女] alex = session.query(Student).filter(Student.name == ‘alex‘).first() print(alex) # 1,alex,男 # 如果想查Alex的上課記錄咋查呢?在上面加一個雙向反查關系 print(alex.my_study_record) # [1,YES,alex, 2,NO,alex]
顧客表有兩個外鍵,兩個外鍵指向同一張表,此時的雙向查詢:
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,String,Integer from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey engine = create_engine("mysql+pymysql://root:mysql8@localhost/mysqltest") Base = declarative_base() # 顧客表Customer有兩個外鍵,訂單地址ID,郵寄地址ID。都關聯了同一張表 class Customer(Base): __tablename__ = ‘customer‘ id = Column(Integer, primary_key=True) name = Column(String(32)) bill_addr_id = Column(Integer, ForeignKey("address.id")) post_addr_id = Column(Integer, ForeignKey("address.id")) bill_addr = relationship("Address", foreign_keys=[bill_addr_id], backref="bill_customers") post_addr = relationship("Address", foreign_keys=[post_addr_id], backref="post_customers") def __repr__(self): return "%s" %(self.name) class Address(Base): __tablename__ = ‘address‘ id = Column(Integer, primary_key=True) detail_address = Column(String(32)) def __repr__(self): return "%s" %(self.detail_address) Base.metadata.create_all(engine)orms模塊
from sqlalchemy.orm import sessionmaker import orms Session_class = sessionmaker(bind=orms.engine) session = Session_class() a1 = orms.Address(detail_address="BeiJing") a2 = orms.Address(detail_address="ShangHai") a3 = orms.Address(detail_address="TianJin") session.add_all([a1, a2, a3]) # 註意這裏賦值的牛逼之處!!!直接用對象進行賦值 c1 = orms.Customer(name="Alex", bill_addr=a1, post_addr=a2) c2 = orms.Customer(name="Jack", bill_addr=a2, post_addr=a3) c3 = orms.Customer(name="Rain", bill_addr=a3, post_addr=a3) session.add_all([c1, c2, c3]) session.commit()init_data模塊
from sqlalchemy.orm import sessionmaker import orms Session_class = sessionmaker(bind=orms.engine) session = Session_class() alex = session.query(orms.Customer).filter(orms.Customer.name=="Alex").first() print(alex.bill_addr, alex.post_addr) # BeiJing ShangHai sh = session.query(orms.Address).filter(orms.Address.detail_address=="ShangHai").first() print(sh.bill_customers) # [Jack]
sqlalchemy外鍵的一些東西