1

这是我的场景。我有一个表格,Books每本书都有一个表格,Questions每个问题都有一个表格Answers

我想要做的是有效地获得给定列表的答案数量Question.id。例子:

# 6,000 Question.id's for Book.id == 1
questions = [0, 1, 2, 3, 4, 5, 6, ..., 6000]

这就是我正在做的事情,事实证明它的效率非常低:

# This takes a couple minutes for it to finish
count = 0
query = QuestionModel.query.filter(QuestionModel.id.in_(questions)).all()

for q in query:
  count += len(list(q.Answers))

# count = 3456

我假设这太慢q.Answers了,因为实际上是在填充数据。

这是我的模型:

class BookModel(db.base):
    __tablename__ = 'books_book'
    __table_args__ = {
        'autoload': True,
        'extend_existing': True,
        'autoload_with': db.instance.engine,
    }
    id = Column(Integer, primary_key=True)
    Chapters = relationship(ChapterModel)
    QuestionMeta = relationship(QuestionMetaModel)

class QuestionMetaModel(db.base):
    __tablename__ = 'questions_questionmeta'
    __table_args__ = {
        'autoload': True,
        'extend_existing': True,
        'autoload_with': db.instance.engine,
    }
    id = Column(Integer, primary_key=True)
    question_id = Column(ForeignKey('questions_question.id'))
    book_id = Column(ForeignKey('books_book.id'))
    chapter_id = Column(ForeignKey('books_chapter.id'))

class QuestionModel(db.base):
    __tablename__ = 'questions_question'
    __table_args__ = {
        'autoload': True,
        'extend_existing': True,
        'autoload_with': db.instance.engine,
    }
    id = Column(Integer, primary_key=True)
    Answers = relationship(AnswerModel)

class AnswerModel(db.base):
    __tablename__ = 'answers_answer'
    __table_args__ = {
        'autoload': True,
        'extend_existing': True,
        'autoload_with': db.instance.engine,
    }
    id = Column(Integer, primary_key=True)
    question_id = Column(ForeignKey('questions_question.id'))

问题:我想要的只是条目数量QuestionModel.Answers,而不是实际数据本身。我将如何做到这一点,所以一个人不需要 2 分钟Book.id?获取Question.id每本书的答案很快,但获取每本书的答案数量Question.id却非常慢。

4

1 回答 1

0

执行joincross BookModelQuestionModelAnswerModel并使用 SQLAlchemy func.count

from sqlalchemy import func

count_query = (session.query(BookModel, QuestionModel, AnswerModel, func.count(AnswerModel.id))
    .select_from(AnswerModel)
    .join(QuestionModel)
    .join(BookModel)
    .group_by(BookModel)
)
于 2019-07-14T23:15:19.777 回答