这是一个示例代码。
文档有很多评论
PostComment扩展评论(使用sqlalchemy多态特征)
某些查询会在len(query.all())
和query.count()
参见下面的主要功能。
发生了什么事?
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table, Column, Integer, Float, Boolean, ForeignKey, String, Unicode, DateTime, Date, UniqueConstraint
from sqlalchemy.orm import relationship, backref
engine = create_engine('mysql://root:root@192.168.59.103:3306/document')
DBSession = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()
Base.metadata.bind = engine
class Document(Base):
__tablename__ = 'document'
id = Column(Integer, primary_key=True)
class Comment(Base):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
type = Column(String(50))
document_id = Column(Integer, ForeignKey('document.id'), primary_key=True)
document = relationship('Document', backref=backref('comments', lazy='dynamic'))
__mapper_args__= {
'polymorphic_identity' : 'comment',
'polymorphic_on' : type,
}
class PostComment(Comment):
__tablename__ = 'post_comment'
id = Column(Integer, ForeignKey('comment.id'), primary_key=True)
ready = Column(Boolean)
__mapper_args__= {
'polymorphic_identity' : 'post_comment',
}
def main():
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
d1 = Document()
DBSession.add(d1)
d2 = Document()
DBSession.add(d2)
c1 = PostComment(document=d1, ready=True)
DBSession.add(c1)
c2 = PostComment(document=d1, ready=True)
DBSession.add(c2)
c3 = PostComment(document=d2, ready=True)
DBSession.add(c3)
c4 = PostComment(document=d2, ready=True)
DBSession.add(c4)
DBSession.commit()
query = d1.comments.filter(PostComment.ready==True)
print len(query.all()) # returns 2
print query.count() # returns 8
if __name__ == '__main__':
main()
更新
http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchemy.orm.query.Query.count
它表示"返回此Query将返回的行数。"。
答案 0 :(得分:1)
为什么你得到8而不是2?因为您得到的查询是笛卡儿产品(8 = 2 * 2 * 2)。
反过来,这是因为您与 dynamic
建立了inheritance
关系,这会从两个表(select
和comment
创建post_comment
)他们之间没有任何断言。
为什么第一个查询只返回2
?好吧,因为你要求实际的映射实例,sqlalchemy
足够聪明,可以过滤掉重复项,尽管基础SQL
语句也会返回8行。
在您的查询中添加join
以解决此问题:
query = d1.comments.join(PostComment).filter(PostComment.ready == True)