0

I have two tables which I am joining together.

class Request(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    client = db.Column(db.Integer, db.ForeignKey('client.id'))
    offerSent = db.Column(db.Boolean)
    (...)

class Client(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    lastname = db.Column(db.String(60))
    prename = db.Column(db.String(40))
    requests = db.relationship('Request', backref='requestClient',   lazy='dynamic')
(...)

So I am joining the two tables:

@app.route('/')
@app.route('/index')
@login_required
def index():
    results = db.session.query(Request, Client).filter(Request.client == Client.id).all()
    return render_template('index.html', title='Start', results=results)

And then I am displaying them:

{% block app_content %}

    <h4>User: {{ current_user.username }}!</h4>

    {% for i in range(0, results|length) %}
       {{ results[i][0].offerSent }} 
       {{ results[i][1].lastname }} 
    {% endfor %}

{% endblock %}

So as you see I have to hardcode the second dimension to get the proper value out of the list (results = [( Request 1, Client 13), (...,...)].

Is there maybe a nicer way to do it? E.g. something like results.request.offerSent and results.client.lastname?

hans2k6
  • 29
  • 5

1 Answers1

0

I believe you can use tuple unpacking within Jinja like this, which seems to be what you are looking for:

{% block app_content %}

    <h4>User: {{ current_user.username }}!</h4>

    {% for req, client in results %}
        {{ req.offerSent }} 
        {{ client.lastname }} 
    {% endfor %}

{% endblock %}

I used req here because Flask's request is part of the Jinja2 standard context

abigperson
  • 5,252
  • 3
  • 22
  • 25
  • Thank you for your answer. I am getting "ValueError: too many values to unpack (expected 2)" which I was fighting with many hours before. Do you have any idea? I am using SQLAlchemy-1.2.0b3 as there is a bug in 1.2.1 regarding a same issue (https://stackoverflow.com/questions/48390207/sql-alchemy-valueerror-too-many-values-to-unpack?rq=1) - even so I don't know if its related to the error regarding your post. – hans2k6 Apr 06 '18 at 09:01
  • Yea I'm not familiar with this bug and it is impossible for me to test this, but I'd expect this to work if results is a list of tuples with 2 values... sorry this did not work!! – abigperson Apr 06 '18 at 15:25
  • Forget the bug I was wrtiting about. I recreated the venv and installed all requirements (latest versions) and now your solution is working fine! Thank you very much! – hans2k6 Apr 12 '18 at 18:45
  • Terrific! Glad you got it sorted out. If you feel the post sufficiently answers your question you can "accept" it as the answer for future readers. – abigperson Apr 12 '18 at 21:13