我正在尝试使用SQLAlchemy-DataTables对jQuery DataTables插件进行数据的服务器端处理,但是在尝试创建DataTables列模型时遇到了一个问题。
我的数据模型类似于:
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
subject = db.Column(db.String(64))
#...
creator_id = db.Column(db.Integer, db.ForeignKey('users.id'))
creator = db.relationship('User', foreign_keys=[creator_id])
created_time = db.Column(db.DateTime(), default=datetime.utcnow)
last_modifier_id = db.Column(db.Integer, db.ForeignKey('users.id'))
last_modifier = db.relationship('User', foreign_keys=[last_modifier_id])
modified_time = db.Column(db.DateTime(), default=datetime.utcnow)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
#...
我的views.py文件(是的,这是一个Flask应用程序)然后看起来像:
@posts.route('/data')
def data():
# Column definition for SQLAlchemy-DataTables
columns = [
ColumnDT(Post.id),
ColumnDT(Post.subject),
ColumnDT(User.username), # for creator
ColumnDT(User.username), # for last modifier... this is the problem
ColumnDT(Post.modified_time)
]
# Query definition
query = db.session.query().\
select_from(Post).\
outerjoin(User, Post.creator_id==User.id).\
outerjoin(User, Post.last_modifier_id==User.id) # second error here
# Request parameters
params = request.args.to_dict()
# Instantiating a DataTable for the query and table needed
rowTable = DataTables(params, query, columns)
# Returns DataTable JSON
return jsonify(rowTable.output_result())
我可以使用指南的代码有两个问题:
答案 0 :(得分:1)
要多次加入同一张桌子,您需要aliases:
export MODE="service"
然后使用所述别名定义列:
In [9]: creator = db.aliased(User)
In [10]: last_modifier = db.aliased(User)
最后,形成查询:
In [11]: columns = [
...: ColumnDT(Post.id),
...: ColumnDT(Post.subject),
...: ColumnDT(creator.username),
...: ColumnDT(last_modifier.username),
...: ColumnDT(Post.modified_time)
...: ]
...: