Search code examples
flaskforeign-key-relationshipflask-sqlalchemyflask-wtforms

Flask: populating a WTform with an SQLalchemy model with relationships


In a Flask app I have this models.py:

 class UserB(Base):
    __tablename__='users'
    id=Column(Integer, primary_key=True)
    username=Column(String(50), nullable=False, unique=True)
    address=relationship("AddressB", uselist=False, backref='user')

class AddressB(Base):
    __tablename__='addresses'
    id=Column(Integer, primary_key=True)
    street= Column(String(150), nullable=True)
    ...
    user_id=Column(Integer, ForeignKey('users.id'))

and I'd like to populate an instance userF of UserF:

class UserF(Form):
username = StringField(validators=[
                ])
street = TextField(validators=[
                Length(min=2, max=150)
                ])

with an instance userB of UserB containing data from Postgresql:

@app.route('/view_user_profile', methods=['GET', 'POST'])
@login_required

def view_user_profile():
    currentUserId=current_user.id

    userB=db.session.query(UserB).get(currentUserId)

    userF=UserF(request.form)

    if (request.method=='GET'):
        #I'd like to populate form with data yet in Postgresql
        userF=UserF(obj=userB)

but doing this way I only populate profileF with username and other data from userB but not with street and other data from addressB. Of course it'd be possible to get userB.adress.street and other addressB fields one by one, but I'd prefer to have a compact solution if possible.


Solution

  • Have a look at the WTForms-Alchemy extension, it supports one-to-one and also one-to-many relations during the form object population. Here is the relevant documentation, and a snippet about how to make it work with Flask-WTF.