• Mysql-Sqlalchemy-ORM-多外键关联


    创建表结构:orm_many_fk.py

    from sqlalchemy import Integer, ForeignKey, String, Column,create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import relationship
    
    Base = declarative_base()#生成orm基类
    
    
    class Customer(Base):
        __tablename__ = 'customer'
        id = Column(Integer, primary_key=True)
        name = Column(String(64))
    
        billing_address_id = Column(Integer, ForeignKey("address.id"))
        shipping_address_id = Column(Integer, ForeignKey("address.id"))
    
        billing_address = relationship("Address", foreign_keys=[billing_address_id])
        shipping_address = relationship("Address", foreign_keys=[shipping_address_id])
    
    
    class Address(Base):
        __tablename__ = 'address'
        id = Column(Integer, primary_key=True)
        street = Column(String(64))
        city = Column(String(64))
        state = Column(String(64))
        def __repr__(self):
            return "<%s >" % (self.street)
    engine = create_engine("mysql+pymysql://root:521521@192.168.71.140/oldboy",
                           encoding='utf-8')  # 可以加echo=True显示数据
    
    #Base.metadata.create_all(engine)
    

     操作数据库:增删改查等操作 orm.api.py

    from day12 import orm_many_fk
    
    from sqlalchemy.orm import sessionmaker
    
    Session_class = sessionmaker(bind=orm_many_fk.engine)
    
    Session =Session_class()#游标
    
    '''插入数据'''
    # addr1 = orm_many_fk.Address(street="Tiantongyuan",city="ChangPing",state="BeiJing")
    # addr2 = orm_many_fk.Address(street="Wudaokou",city="HaiDian",state="BeiJing")
    # addr3 = orm_many_fk.Address(street="YanJiao",city="LangFang",state="HB")
    #
    # Session.add_all([addr1,addr2,addr3])
    # c1 = orm_many_fk.Customer(name="WanPang",billing_address=addr1,shipping_address=addr2)
    # c2 = orm_many_fk.Customer(name="goupang",billing_address=addr3,shipping_address=addr3)
    
    # Session.add_all([c1,c2])
    
    '''查看数据'''
    obj = Session.query(orm_many_fk.Customer).filter_by(name="goupang").first()
    print(obj.name,obj.billing_address, obj.shipping_address)
    Session.commit()
    
  • 相关阅读:
    Shiro【常用的自定义】
    Shiro【重要概念总结】
    Shiro【自定义Realm实战】
    Shiro【内置Realm实操】
    Shiro【快速上手】
    Shiro【初识】
    面向对象【抽象类和接口的区别】
    面向对象【多态中的成员访问特点】
    Kafka2.12-2.5.0在windows环境的安装 启动 通信测试
    CentOS.iso 下载地址收纳整理
  • 原文地址:https://www.cnblogs.com/fuyuteng/p/9318505.html
Copyright © 2020-2023  润新知