2012-05-31 45 views
3

我想創建一個查詢,將返回數據庫中的所有節目按用戶數量排序,將其作爲收藏。燒瓶SQLAlchemy的訂單顯示的關注人數

簡體工作代碼:

from flask import Flask 
from flask.ext.sqlalchemy import SQLAlchemy 
from sqlalchemy.sql import func 
import logging 

app = Flask(__name__) 
db = SQLAlchemy(app) 

logging.basicConfig() 
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) 

favorite_series = db.Table('favorite_series', 
     db.Column('user_id', db.Integer, db.ForeignKey('users.id')), 
     db.Column('series_id', db.Integer, db.ForeignKey('series.id'))) 

class User(db.Model): 
    __tablename__ = 'users' 

    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String) 
    favorite_series = db.relationship('Serie', secondary=favorite_series, 
      backref=db.backref('users', lazy='dynamic')) 

    def __repr__(self): 
     return '<User {0}>'.format(self.name) 


class Serie(db.Model): 
    __tablename__ = 'series' 

    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String) 

    def __repr__(self): 
     return '<Serie {0}>'.format(self.name) 

u1 = User() 
u1.name = 'user1' 

u2 = User() 
u2.name = 'user2' 

u3 = User() 
u3.name = 'user3' 

s1 = Serie() 
s1.name = 'Serie1' 

s2 = Serie() 
s2.name = 'Serie2' 

s3 = Serie() 
s3.name = 'Serie3' 

s4 = Serie() 
s4.name = 'Serie4' 

s5 = Serie() 
s5.name = 'Serie5' 

u1.favorite_series.extend([s1, s3, s5]) 
u2.favorite_series.extend([s1, ]) 
u3.favorite_series.extend([s1, s2, s3]) 

u1.favorite_series.extend([s1, s2]) 
db.session.add(u1) 
db.session.add(u2) 
db.session.add(u3) 
db.session.add(s1) 
db.session.add(s2) 
db.session.add(s3) 
db.session.add(s4) 
db.session.add(s5) 
db.create_all() 
db.session.commit() 

我嘗試使用檢索它們:

shows = Serie.query.join(Serie.users).order_by(func.count(Serie.users)).all() 

print shows 

但是,這將引發錯誤的SQL語法,我想尋找的東西,但遲遲不來與任何工作。

任何幫助,將不勝感激。

+0

添加完整堆棧跟蹤。 – Denis

+3

這可能是一個重複http://stackoverflow.com/questions/7954696/elixir-sqlalchemy-order-by-count-of-onetomany-relationship – madjar

+0

這是不同的,因爲我使用ManyToMany,我使用交叉表,該示例已外鍵。 – TrueFurby

回答

2

工作液:

sub = db.session.query(favorite_series.c.series_id, func.count(favorite_series.c.user_id).label('count')).group_by(favorite_series.c‌​.series_id).subquery() 
shows = db.session.query(Serie, sub.c.count).outerjoin(sub, Serie.id == sub.c.series_id).order_by(db.desc('count')).all()