wtforms-alchemy - 用关系数据预填充表单怎么样?

wtforms-alchemy - what about pre-populating the form with relationship data?

所以...

这个:

model_dictionary = model.as_dict() # some kind of dictionary
form = TheModelsForm(**model_dictionary) # https://wtforms-alchemy.readthedocs.io/en/latest/advanced.html
form.populate_obj(model)
return form

这让我用模型中 db.Columns 的字段预填充模型的表单。嗯..模型上的 db.relationships 怎么样?

以上代码没有预先填充关系字段;他们出现但留空。无论我是否强制在 model_dictonary 中包含关系值,只有 db.Column 字段会预先填充值(例如,model_dictionary['key_from_other_object'] = associated价值)。

这能实现吗? --在此找不到任何内容..

编辑: 我用以下方法解决了最初的问题:

form = TheModelsForm(obj=model)
form.populate_obj(model)
return form

现在我想弄清楚如何让位置模型上的事件真正显示在位置表单上...

class Event(Base):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    location_id = db.Column(db.Integer, db.ForeignKey('location.id'))

class Location(Base):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    events = db.relationship('Event', backref=db.backref('events'))

我确信我注释掉的所有内容都不起作用是有逻辑原因的。我得到 'NoneType' object is not iterable

class EventForm(ModelForm):
    class Meta:
        model = models.Event

    location_id = fields.SelectField(u'Location', coerce=int)


 class LocationForm(ModelForm):
        class Meta:
            model = models.Location

        #events = fields.SelectField(u'Event', choices=[(g.id, g.selector) for g in models.Event.query.all()], coerce=int)

        # events = fields.SelectMultipleField('Event', 
        #     choices=[(g.id, g.selector) for g in models.Event.query.all()],
        #     coerce=int,
        #     option_widget=widgets.CheckboxInput(),
        #     widget=widgets.ListWidget(prefix_label=False)
        #     )

        #events = ModelFieldList(fields.FormField(EventForm))

使用 SelectMultipleField 和 SelectField 找错了树..

相反,

wtforms_alchemy.fields.QuerySelectMultipleField@https://media.readthedocs.org/pdf/wtforms-alchemy/latest/wtforms-alchemy.pdf

this post,有助于显示用法,@ WTForms QuerySelectMultipleField Not sending List

解决了我的问题..

..以

结束
class LocationForm(ModelForm):
    class Meta:
        model = models.Location

    events = wtforms_alchemy.fields.QuerySelectMultipleField('Event', 
        query_factory=lambda: models.Event.query.order_by(models.Event.name).all(), 
        get_label= lambda x: x.name,
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False)
        )