Flask:使用具有关系的 SQLalchemy 模型填充 WTform

Flask: populating a WTform with an SQLalchemy model with relationships

在 Flask 应用程序中我有这个 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'))

我想填充 UserF 的实例 userF:

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

UserB 的实例 userB 包含来自 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)

但是这样做我只使用用户名和来自 userB 的其他数据填充 profileF,而不使用来自地址 B 的街道和其他数据。当然可以一一获取 userB.adress.street 和其他 addressB 字段,但如果可能的话,我更希望有一个紧凑的解决方案。

查看有关如何使其与 Flask-WTF 一起工作的 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