Return SQLAlchemy AppenderBaseQuery 对象中的元素到 Flask-WTForm 字段

Return elements in SQLAlchemy AppenderBaseQuery object to Flask-WTForm field

我正在开发表单的 "edit" 功能。呈现表单时,字段应填充数据库中存储的数据。此字段之一作为 SQlAlchemy AppenderBaseQuery 对象返回。这会导致在字段中预填充查询语句,而不是查询结果。

如何使用对象中的元素预填充表单?

form = MyForm(obj=MyObject)

if form.validate_on_submit():
    form.populate_obj(MyObject)

字段定义为 StringField。

注意: 我正在传递 MyObject 以预填充表单,因为 WTForm 有一个问题 form.Field.data 根本没有更新。

form = MyForm()
form.Field.data = "test" #Pre-populate Field with "test"

if validate_on_submit():
    MyObject.Field = Form.Field.data #Assign data in Field to MyObject
    #...

我的 Object.Field 不会用新的 Form.Field.data 更新,不知道为什么。

正如 n-Holmes 在评论中所建议的那样:

# Do not initiate the form with object
form = MyForm() 

# Split logic to 'GET' and 'POST request'
if request.method == 'GET'
    MyForm.Field.Data = ', '.join([element.attribute for element in MyForm.Field.all()]

    # MyForm.Field is an AppenderBaseQuery Object >> Returns a query statement
    # MyForm.Field.all() returns a list of Objects
    # The list comprehension returns a list of a specific attribute for each object
    # The .join combines the list to a string, separated by ", "
    # This entire thing is pre-populated onto the form
    # Eg: "Attribute01, Attribute02, Attribute03"

if validate_on_submit:
    MyObject.Field = FunctionToUpdateField(form.Field.data)

    # form.Field.data will be a string
    # FunctionToUpdateField compares above string with what is stored in db ...
    # determines which elements to add / remove