• sqlalchemy的orm的多对多,正向查询,反向查询


    flask的SQLAlchemy

    """
    	安装:
        pip install  sqlalchemy
    """
    

    models.py

    # pip install  sqlalchemy
    import datetime
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index
    from sqlalchemy.orm import relationship
    Base = declarative_base()
    
    class Users(Base):
        __tablename__ = 'users'  # 数据库表名称
        id = Column(Integer, primary_key=True)  # id 主键
        name = Column(String(32), index=True, nullable=False)  # name列,索引,不可为空
        age = Column(Integer)
        #email = Column(String(32), unique=True)
        #datetime.datetime.now#不能加括号,加了括号,以后永远是当前时间
        #ctime = Column(DateTime, default=datetime.datetime.now)
        #extra = Column(Text, nullable=True)
    
        __table_args__ = (
            # UniqueConstraint('id', 'name', name='uix_id_name'), #联合唯一
            # Index('ix_id_name', 'name', 'email'), #索引
        )
    
        def __repr__(self):  # 作用类似于__str__, 但是__repr__的作用更加底层,__str__则打印不出来
            return self.name
    
    
    class Hobby(Base):
        __tablename__ = "hobby"
        id = Column(Integer, primary_key=True)
        catption = Column(String(50), default="双色球")
    
    
    class Person(Base):
        __tablename__ = "person"
        nid = Column(Integer, primary_key=True)
        name = Column(String(32))
        #hobby指的是tablename而不是Hobby类名,
        hobby_id = Column(Integer,ForeignKey("hobby.id"))
    
        # 跟数据库没有关系,不会新增加字段,只能用于快速的链表查询操作
        #relationship的第一个参数,是类名,第二个参数backref,用于反向查询
        hobby =relationship("Hobby", backref="pres")
    
        def __repr__(self):
            return  self.name
    
    
    # # 一个男孩可以喜欢多个女孩,一个女孩也可以喜欢多个男孩
    class Boy2Girl(Base):
        __tablename__ = "boy2girl"
        id = Column(Integer, primary_key=True)
        girl_id = Column(Integer,ForeignKey("girl.id"))
        boy_id = Column(Integer,ForeignKey("boy.id"))
    
    
    class Girl(Base):
        __tablename__ = "girl"
        id  = Column(Integer,primary_key=True)
        name =  Column(String(100),nullable=False)
    
        def __repr__(self):
            return self.name
    
    class Boy(Base):
        __tablename__ = "boy"
        id = Column(Integer, primary_key=True)
        name = Column(String(100), nullable=False)
        #secondary=boy2girl 中间表的表名
        girl = relationship("Girl",secondary="boy2girl",backref = "boys")
    
        def __repr__(self):
            return self.name
    
    
    def init_db():
        """
        根据类创建数据库表
        :return:
        """
        engine = create_engine(
            "mysql+pymysql://root:123456@127.0.0.1:3306/python13?charset=utf8",
            #"什么数据库(mysql,orcal)+用什么取链接数据库(pymysql)://数据库用户名:密码@mysqlip:端口/数据库名?charset=字符集"
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    
        Base.metadata.create_all(engine)
    
    def drop_db():
        """
        根据类删除数据库表
        :return:
        """
        engine = create_engine(
             "mysql+pymysql://root:123456@127.0.0.1:3306/python13?charset=utf8",
            max_overflow=0,  # 超过连接池大小外最多创建的连接
            pool_size=5,  # 连接池大小
            pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
            pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
        )
    
        Base.metadata.drop_all(engine)
    
    if __name__ == '__main__':
        drop_db()
        init_db()
    

    orm的多对多

    from sqlalchemy.orm import sessionmaker
    from sqlalchemy import create_engine
    from models import Boy,Boy2Girl,Girl
    
    engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/python13", max_overflow=0, pool_size=5)
    Connection = sessionmaker(bind=engine)
    #
    # # 每次执行数据库操作时,都需要创建一个Connection
    session = Connection()
    #
    #添加
    session.add_all([
        Boy(name="tank"),
        Boy(name="sean"),
        Girl(name="仓老师"),
        Girl(name="小泽老师")
    ])
    
    
    
    b2g = Boy2Girl(boy_id=1, girl_id=2)
    session.add(b2g)
    b2g = Boy2Girl(boy_id=2, girl_id=1)
    session.add(b2g)
    session.commit()
    session.close()
    
    
    # 正向插入
    boy = Boy(name="alen")
    boy.girl=[Girl(name="迪丽热巴"),Girl(name="三上悠亚")]
    session.add(boy)
    session.commit()
    
    # 反向插入
    girl = Girl(name="丹丹")
    girl.boys=[Boy(name="吴彦祖"),Boy(name="鹿晗")]
    session.add(girl)
    session.commit()
    
    
    # # 使用relationship的关系,正反向查
    
    b = session.query(Boy).filter(Boy.name == "alen").first()
    print(b.name)
    print(b.girl)
    
    # #反向查询
    g = session.query(Girl).filter(Girl.name=="丹丹").first()
    print(g.name)
    print(g.boys)
    
  • 相关阅读:
    httpclient的并发连接问题
    Java中使用多线程、curl及代理IP模拟post提交和get访问
    有强大的cURL,忘掉httpclient的吧!
    JavaScript正则表达式在不同浏览器中可能遇到的问题
    Meta对照表
    IntelliJ IDEA 下的svn配置及使用的非常详细的图文总结
    虚拟机centos7服务器下,启动oracle11g数据库和关闭数据库
    Step 4: Install and Configure Databases
    docker 中部署一个springBoot项目
    docker保存对容器的修改
  • 原文地址:https://www.cnblogs.com/yafeng666/p/12542542.html
Copyright © 2020-2023  润新知