如何在Flask中的jinja2中显示db.session.query结果

时间:2016-04-14 23:02:57

标签: python flask sqlalchemy jinja2

我有这个:

class User(db.Model):
    __tablename__ = 'User'
    user_id = db.Column(db.Integer, primary_key=True)
    user_name = db.Column(db.String(100), unique=True)
    user_password = db.Column(db.String(100), nullable=False)
    companies = db.relationship('Company', backref="User", lazy='dynamic')

class Company(db.Model):
    __tablename__ = 'Company'
    company_id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('User.user_id'))
    company_name = db.Column(db.String(100), unique=True)
    branches = db.relationship('Branch', backref="Company", lazy='dynamic')

class Branch(db.Model):
    __tablename__ = 'Branch'
    branch_id = db.Column(db.Integer, primary_key=True)
    company_id = db.Column(db.Integer, db.ForeignKey('Company.company_id'))
    branch_name = db.Column(db.String(100), unique=True)
    secondary_users = db.relationship('Secondary_User', backref="Branch", lazy='dynamic')

现在,我想要一个特定用户的分支列表

@app.route('/admin', methods=['GET', 'POST'])
@login_required
def admin():
    current_user_id = request.args.get('user_id')
    current_user_branches = db.session.query(User, Company, Branch).filter(Branch.company_id == Company.company_id).filter(Company.user_id == User.user_id).filter(User.user_id == current_user_id).all()
    return render_template('admin_branch.html', branches_list=current_user_branches)

我的问题是我无法在admin_branch.html:

中显示结果
<thead>
<tr>
    <th>Branch Name</th>
    <th>Branch ID</th>
</tr>

<tbody>
  {% if branches_list is not none %}
      {% for b in branches_list %}
          <tr><td>{{ b.branch_name }}</td><td>{{ b.branch_id }}</td></tr>
      {% endfor %}
   {% else %}
      <tr><td>No hay sucursales registradas</td></tr>
   {% endif %}

但这是两栏中的内容:

(<Company u'MyCompanyTest'>, <User u'admin'>, <models.Branch object at 0x7f8fe5901390>)

我不知道如何处理这些内容。请帮助我,谢谢。

1 个答案:

答案 0 :(得分:2)

{% for company,user,branch in branches_list %}
      <tr><td>{{ branch.branch_name }}</td><td>{{ branch.branch_id }}</td></tr>
{% endfor %}

我认为你想要的......或者如果你不想改变你的模板然后改变它,所以你只是通过分支

current_user_branches = [item[-1] for item in db.session.query(User, Company, Branch).filter(Branch.company_id == Company.company_id).filter(Company.user_id == User.user_id).filter(User.user_id == current_user_id).all()]

或者更好地进行正确的查询

my_company_ids = [company.id for company in current_user.companies.all()]
db.session.query(Branch).where(Branch.company_id._in(my_company_ids))

我认为这至少是正确的......

您也可以从当前用户

构建它
user_branches = set([branch for company in current_user.companies.all() for branch in company.Branches.all()])

我还鼓励你选择一个命名约定并坚持下去(可能会使用类似于编码的服务,这会让你知道命名不佳的变量)