zoukankan      html  css  js  c++  java
  • ORM多对多的实现

    #coding=utf-8
    from sqlalchemy import Table, Column, Integer,String,DATE, ForeignKey
    from sqlalchemy.orm import relationship
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    
    engine = create_engine("mysql+pymysql://root:123456@192.168.70.129/test1?charset=utf8",
                           encoding='utf-8', echo=False)
    
    Base = declarative_base()
    
    #这张表不会手动去维护,用户不需要关注,
    book_m2m_author = Table('book_m2m_author', Base.metadata,
                            Column('book_id',Integer,ForeignKey('books.id')),
                            Column('author_id',Integer,ForeignKey('authors.id')),
                            )
    
    class Book(Base):
        __tablename__ = 'books'
        id = Column(Integer,primary_key=True)
        name = Column(String(64))
        pub_date = Column(DATE)
        authors = relationship('Author',secondary=book_m2m_author,backref='books') #secondary 意思是查找的时候通过book_m2m_author去查Author
    
        def __repr__(self):
            return self.name
    
    class Author(Base):
        __tablename__ = 'authors'
        id = Column(Integer, primary_key=True)
        name = Column(String(32))
    
        def __repr__(self):
            return self.name
    
    Base.metadata.create_all(engine)
    
    
    #写入数据
    Session_class = sessionmaker(bind=engine)
    session = Session_class()
    # b1 = Book(name="bbu1")
    # b2 = Book(name="bbu2")
    # b3 = Book(name="bbu3")
    #
    # a1 = Author(name="people1")
    # a2 = Author(name="people2")
    # a3 = Author(name="peo3ple")
    #
    # b1.authors = [a1, a2]
    # b2.authors = [a1, a2, a3]
    # b3.authors = [a1,a2,a3]
    # session.add_all([b1, b2, b3, a1, a2, a3])
    # session.commit()
    
    #查询
    obj = session.query(Author).filter( Author.name == 'people1').all()
    print obj[0].books
    book_obj = session.query(Book).filter( Book.id == 1).all()
    print book_obj[0].authors
    
  • 相关阅读:
    nginx 配置以及常用命令
    django TypeError: 'module' object is not callable
    Django Meta内部类选项
    安装MySQL后要做的事
    MySQL存储引擎
    kali linux 2018.2 mysql密码修改后无效,外部无法连接问题。
    Django中CSS加载background url('')问题
    升级OPENSSH 和 OPENSSL
    Git创建仓库的方法(github翻译)
    Git标签(版本)管理
  • 原文地址:https://www.cnblogs.com/qiangayz/p/8685349.html
Copyright © 2011-2022 走看看