2013-07-27 1 views
0

코스와 코멘트의 두 클래스가 있습니다. 각 코스의 댓글 수에 따라 코스 목록을 표시하고 싶습니다. 예를 들어, 가장 많은 수의 의견을 가진 강좌가 목록의 첫 번째 여야합니다 .... 누군가가 저에게 효율적인 질의를 찾도록 도와주십시오. 감사.코스 목록을 각 코스 설명의 수만큼 표시하십시오.

class Course(db.Model): 
id = db.Column(db.Integer, primary_key = True) 
course_name =db.Column(db.String(120)) 
course_description = db.Column(db.Text) 
course_comments = db.relationship('Comment', backref ='course', lazy ='dynamic') 





class Comment(db.Model): 
id = db.Column(db.Integer, primary_key = True) 
comment_date = db.Column(db.DateTime, default=db.func.now()) 
comment = db.Column(db.Text) 
course_id = db.Column(db.Integer, db.ForeignKey('course.id')) 
user_id = db.Column(db.Integer, db.ForeignKey('user.id')) 

답변

0

SQL의 관점에서 원하는 것은 그룹의 인스턴스 수를 계산 한 다음 그 계산에 따라 정렬하는 것입니다. 이 질문은 몇 가지 배경 제공 :

SELECT course_id, count(*) 
FROM comment 
GROUP BY course_id 
ORDER BY count(*); 

이 당신에게 물론 의견의 숫자로 분류 코멘트 테이블에서 아이디의를 제공합니다

Counting the number of child records in a one-to-many relationship with SQL only 그래서 SQL에서 당신이 원하는 생각을 뭔가 같다. 이 대답은 sqlalchemy에서이 작업을 수행하는 방법을 보여줍니다. https://stackoverflow.com/a/4086229/1216837

import desc 
import func.count 
import order_by 

session.query(Comment.course_id,func.count(Comment.course_id)).\ 
    group_by(Comment.course_id).\ 
    order_by(desc(func.count(Comment.course_id))).\ 
    all() 
+0

완벽하고 고맙습니다. –