问题
I have a table called SectionAttempt which has many QuestionAttempts
I want to display a computed field 'total_count' that is the number of question attempts for the SectionAttempt WITHOUT loading all the questionAttempts.
Looking online , I found this:
select([func.count()],
QuestionAttempt.__table__.c.section_attempt_id==SectionAttempt.__table__.c.id)
.correlate(SectionAttempt.__table__)
.as_scalar()
I am not 100% sure why this works, but it is working when I query like this:
test_attempt = (SOMEQUERY
.undefer(SectionAttempt.question_attempt_total_count)).one())
I have questions:
- what is .correlate doing here.
- The way it is added to the model, makes me have to import my QuestionAttempt model, which is prone to cyclic import issues (what if I have to do something similar on my QuestionAttempt model ). How can I retain the functionality but either change to a string based reference (like we do for relationships), or inside a function (so that I can import Question Attempt inside the function instead of globally)
来源:https://stackoverflow.com/questions/54168059/count-on-related-model-as-hybrid-property