0

Here are my models:

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)

And from the template:

{% for entry in entries %}
<td>{{ entry.actions.first().location }}</td>
{% endfor %}

This page displays all rows in the Entry table that share a specific "manifest" (an alphanumeric identifier). So you can see my query in routes.py starts:

entries = Entry.query.filter_by(manifest=manifest_to_view)...

For each row from the Entry table, I also need to display the most recent location from the related Action table, but my current line displays the wrong location:

{{ entry.actions.first().location }}

Is there a way to sort locations by the Action.action_date column using order_by() instead of using first()? Or any way to print the most recent location?

Thanks.

Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67
The Picard
  • 51
  • 4

1 Answers1

5

found the answer here: SQLAlchemy - order_by on relationship for join table

I just had to change the relationship in model.py

actions = db.relationship('Action', backref='entry', order_by="desc(Action.id)", lazy='dynamic')
The Picard
  • 51
  • 4