pythonflasksqlalchemyflask-sqlalchemyassociated-object

Accessing extra data in a sqlalchemy associated object


The User object can be involved with a Project in many different ways, specified by Job association table. In my template file, I'm trying to loop through all of the projects in current_user.projects and with each one, specify what the Job was for that user in that project... but I can't get the syntax right.

MODELS

class Project(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(80))
    users = db.relationship("Job", back_populates="project")

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(155))
    last_name = db.Column(db.String(155))
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    projects = db.relationship("Job", back_populates="user")

# defines a user's role related to each assigned project
class Job(db.Model):
    __tablename__ = 'job'
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), primary_key=True)
    job = db.Column(db.String(50))
    user = db.relationship("User", back_populates="projects")
    project = db.relationship("Project", back_populates="users")

    def __init__(self, user_id, project_id, job="client"):
        self.user_id = user_id
        self.project_id = project_id
        self.job = job

VIEW

@app.route('/projects')
@login_required
def projects():
    projects = Project.query.join(Job).filter_by(user_id=current_user.id).all() 
    # current_user.projects would probably do the same thing            
    return render_template('project/projects.html', projects=projects)

TEMPLATE

<div class="accordion style-two gradient-bg">
    <div class="panel-group" id="accordion-2">
        {% for project in projects %}
        <div class="panel panel-default">
            <!-- Accordian Title -->
            <div class="panel-heading">
                <div class="panel-title">
                    <a class="accordion-toggle collapsed" href="#{{ project.id }}" data-parent="#accordion-2" data-toggle="collapse" aria-expanded="false">
                        {{ project }} - HELP NEEDED HERE--> ({{ project.user[0].job }})
                    </a>
                </div>
            </div>
            <!-- Accordian Detail -->
            <div id="{{ project.id }}" class="panel-collapse collapse">
                <div class="panel-body">
                    <div class="container">
                        <div class="row">
                        <p>Lorem ipsum dolor sit amet, ei vis iriure phaedrum, sea no regione delicata sadipscing. Minim imperdiet vix ad, pro ei utinam dicunt epicurei. Vide affert debitis has ex. Vel ut consul molestiae pertinacia. Duo graeci dictas consulatu in, ei veniam singulis qui, decore numquam duo id.</p>                        
                        <p>Prima tritani veritus id pro, elitr hendrerit comprehensam ei per. Doming integre aliquando has at. Ea eam aeterno lobortis, ea est mutat laudem semper. Pertinax urbanitas nec ne, quo aliquip voluptaria scriptorem ut. Ut mel tractatos reprimique contentiones, adhuc nulla apeirian usu no, mel imperdiet molestiae abhorreant ut.</p> 
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
   </div>
</div>

As shown above, I have project.users[0].job which will show the correct information because I have just one user in the system. How can I specify on the template level that I'm looking for the job associated with the the current_user as I'm looping through projects? Thanks!


Solution

  • As suggested in the comments, the easiest way is to simply query the associated table to begin with: projects = Job.query.filter_by(user_id=current_user.id).all()

    I have ready access to each Project referenced (project.project) and can also get the details of the job (project.job).