order_by()与Flask-SQLAlchemy相关的表

时间:2018-03-01 04:59:30

标签: python sql flask flask-sqlalchemy

以下是我的模特:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mapview);


    htmlWebView = (WebView) findViewById(R.id.webview);



    htmlWebView.setWebChromeClient(new WebChromeClient());
    htmlWebView.setInitialScale(80);
    WebSettings webSetting = htmlWebView.getSettings();
    //htmlWebView.clearCache(true);



    webSetting.setJavaScriptEnabled(true);
    webSetting.setSupportZoom(true);
    webSetting.setLoadWithOverviewMode(true);
    webSetting.setBuiltInZoomControls(true);
    webSetting.setDisplayZoomControls(true);

    htmlWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    htmlWebView.setScrollbarFadingEnabled(false);
    htmlWebView.loadUrl(URL);

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'))

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)

此页面显示Entry表中共享特定&#34;清单&#34;的所有行。 (字母数字标识符)。因此,您可以在{% for entry in entries %} <td>{{ entry.actions.first().location }}</td> {% endfor %} 开始查看我的查询:

routes.py

对于Entry表中的每一行,我还需要显示相关Action表中的最新entries = Entry.query.filter_by(manifest=manifest_to_view)... ,但我当前行显示错误的位置:

location

是否可以使用{{ entry.actions.first().location }} 而不是使用order_by()按Action.action_date列对位置进行排序?或者以任何方式打印最近的位置?

感谢。

1 个答案:

答案 0 :(得分:1)

在这里找到答案:SQLAlchemy - order_by on relationship for join table

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

actions = db.relationship('Action', backref='entry', order_by="desc(Action.id)", lazy='dynamic')