[英]SQLAlchemy / Flask - Get number of rows in relationship table
這是我的情況。 我有一個表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
的條目數量 ,而不是實際數據本身。 我將如何完成這項工作,因此一個Book.id
不需要2分鍾? 抓住每本書的Question.id
很快,但是抓住每一Question.id
的答案數量卻很慢。
執行join
跨BookModel
, QuestionModel
和AnswerModel
和使用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)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.