sqlalchemy与“ len(query.all())”和“ query.count()”的值不同

发布于 2021-01-29 17:26:49

这是示例代码。

一个文档有很多评论

PostComment扩展注释(具有sqlalchemy多态功能)

某些查询在len(query.all())和之间返回不同的结果query.count()

  • sqlalchemy版本:1.0.8
  • mysql版本:5.6.25

请参阅下面的主要功能。

发生了什么?

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

它说:“返回此查询将返回的行数。”。

关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    为什么得到的结果是8而不是2?因为您得到的查询是 笛卡尔积 (8 = 2 * 2 * 2)。
    反过来,发生这种情况是因为您 与之间dynamic关系,该关系
    从两个表(和)中inheritance创建的selectcomment并且post_comment它们之间没有任何谓词。

    为什么第一个查询只返回2?好吧,因为您要查询实际的映射实例,所以它sqlalchemy很聪明,可以过滤出重复项,尽管基础SQL语句也确实返回了8行。

    join在查询中添加来解决此问题:

    query = d1.comments.join(PostComment).filter(PostComment.ready == True)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看