Count on related model as hybrid property

拜拜、爱过 提交于 2019-12-13 00:25:17

问题


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:

  1. what is .correlate doing here.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!