我有两张桌子:
class Shops(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(255))
order = db.relationship('Order', backref = 'purchased', lazy = 'dynamic')
class Order(db.Model):
id = db.Column(db.Integer, primary_key = True)
date = db.Column(db.DateTime)
shop = db.Column(db.Integer, ForeignKey('shop.id'))
我想根据订单获得最畅销的商店,如下:
query = db.session.query(Shops.name.label('TopShop'),Order,func.max(func.count(Order.shop)))
出现以下错误:
ProgrammingError: (ProgrammingError) (1111, u'Invalid use of group function')
请问正确的指示?
答案 0 :(得分:1)
订单数量
的顶级商店。subq = (session.query(Order.shop, func.count(Order.id).label("num_orders")).
group_by(Order.shop)).subquery()
q = session.query(Shops).join(subq, Shops.id == subq.c.shop).order_by(subq.c.num_orders.desc())
# top 1
print q.first()
# top 5
print q[:5]