2015-04-14 149 views
0

你好我想翻譯下面比較簡單的查詢SQLAlchemy的,但我得到SQL查詢翻譯SQLAlchemy的

('Unexpected error:', <class 'sqlalchemy.exc.InvalidRequestError'>) 

SELECT model, COUNT(model) AS count FROM log.logs 
WHERE SOURCE = "WEB" AND year(timestamp) = 2015 AND month(timestamp) = 1 
and account = "Test" and brand = "Nokia" GROUP BY model ORDER BY count DESC limit 10 

這是我寫的,但它無法正常工作。哪裏不對 ?

devices = db.session.query(Logs.model).filter_by(source=source).filter_by(account=acc).filter_by(brand=brand).\ 
      filter_by(year=year).filter_by(month=month).group_by(Logs.model).order_by(Logs.model.count().desc()).all() 
+0

這裏的count()調用是否正確? 'Logs.model.count().desc()'它應該按'count'列排序嗎? – dm03514

回答

1

從您的代碼示例中可以看出有點難,但希望下面的代碼是正確的SQLAlchemy。嘗試:

from sqlalchemy.sql import func 

devices = (db.session 
      .query(Logs.model, func.count(Logs.model).label('count')) 
      .filter(source=source) 
      .filter_by(account=acc) 
      .filter_by(brand=brand) 
      .filter_by(year=year) 
      .filter_by(month=month) 
      .group_by(Logs.model) 
      .order_by(func.count(Logs.model).desc()).all()) 

請注意,我已經封閉在(...)查詢,以避免在每行的末尾使用\