order_by() 与 Flask-SQLAlchemy 相关的表

The*_*ard 0 python sql flask flask-sqlalchemy

这是我的模型:

class Entry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    manifest = db.Column(db.String, default=None, nullable=True)
    name = db.Column(db.String, default=None, nullable=True)
    actions = db.relationship('Action', backref='entry', lazy='dynamic')

class Action(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    action_date = db.Column(db.DateTime, default=datetime.utcnow, nullable=True)
    location = db.Column(db.String, default=None, nullable=True)
    entry_id = db.Column(db.Integer, db.ForeignKey('entry.id'))
Run Code Online (Sandbox Code Playgroud)

routes.py

@app.route('/manifests/<manifest_to_view>')
@login_required
def view_manifest(manifest_to_view):
    page = request.args.get('page', 1, type=int)
    entries = Entry.query.filter_by(manifest=manifest_to_view).paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('view_manifest', manifest_to_view=manifest_to_view, page=entries.next_num) \
        if entries.has_next else None
    prev_url = url_for('view_manifest', manifest_to_view=manifest_to_view, page=entries.prev_num) \
        if entries.has_prev else None
    return render_template("view_manifest.html", title='View Manifest', manifest_to_view=manifest_to_view, entries=entries.items, next_url=next_url, prev_url=prev_url)
Run Code Online (Sandbox Code Playgroud)

从模板中:

{% for entry in entries %}
<td>{{ entry.actions.first().location }}</td>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

此页面显示条目表中共享特定“清单”(字母数字标识符)的所有行。所以你可以在routes.py开始时看到我的查询:

entries = Entry.query.filter_by(manifest=manifest_to_view)...
Run Code Online (Sandbox Code Playgroud)

对于 Entry 表中的每一行,我还需要显示location相关 Action 表中的最新行,但我当前的行显示了错误的位置:

{{ entry.actions.first().location }}
Run Code Online (Sandbox Code Playgroud)

有没有办法按 Action.action_date 列使用order_by()而不是使用对位置进行排序first()?或者有什么方法可以打印最近的位置?

谢谢。

The*_*ard 5

在这里找到答案:SQLAlchemy - order_by 连接表的关系

我只需要改变 model.py 中的关系

actions = db.relationship('Action', backref='entry', order_by="desc(Action.id)", lazy='dynamic')
Run Code Online (Sandbox Code Playgroud)