2013-02-21 2 views
1

SQLAlchemy의 작동 방식은 여전히 ​​혼란 스럽습니다. 현재이 쿼리는 다음과 같습니다.Flask-SQLAlchemy에서 카운트 선택

SELECT cast(a.product_id as bigint) id, cast(count(a.product_id) as bigint) itemsSold, cast(b.product_name as character varying) 
    from transaction_details a 
    left join product b 
    on a.product_id = b.product_id 
    group by a.product_id, b.product_name 
    order by itemsSold desc; 

Flask tho에서 어떻게 변환되는지 잘 모르겠습니다.

답변

3

SQLAlchemy를 처음 접하는 경우 Object Relational TutorialSQL Expression Language Tutorial을 모두 읽고 작동 방식을 익히십시오. Flask-SQLAlchemy 확장을 사용하기 때문에 앞서 언급 한 자습서의 예제에서 가져온 많은 이름은 SQLAlchemy 클래스 (보통 Flask-SQLAlchemy 예제에서는 db)라는 인스턴스를 통해 액세스 할 수 있습니다. SA로 변환하면 SQL 쿼리가 다음과 같이 보일 것입니다. (확인되지 ​​않음)

# Assuming that A and B are mapped objects that point to tables a and b from 
# your example. 
q = db.session.query(
    db.cast(A.product_id, db.BigInteger), 
    db.cast(db.count(A.product_id), db.BigInteger).label('itemsSold'), 
    db.cast(B.product_name, db.String) 
# If relationship between A and B is configured properly, explicit join 
# condition usually is not needed. 
).outerjoin(B, A.product_id == B.product_id).\ 
group_by(A.product_id, B.product_name).\ 
order_by(db.desc('itemsSold')) 
+0

최고 : 고맙습니다. –