ORM多对多的实现

Posted 梦中琴歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:[email protected]/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

 

以上是关于ORM多对多的实现的主要内容,如果未能解决你的问题,请参考以下文章

Django

Hibernate-ORM:12.Hibernate中的多对多关联关系

Django 补充ORM多对多正向查询

Django中ORM多对多表的操作

django ORM中的RelatedManager(关联管理器)

ORM练习项目-图书管理系统(BMS)实现细节