我有一个Event
类,一对多Locations
。当我在WTForms-Alchemy生成的表单中编辑Location
的数据并按文档填充对象时,它似乎插入一条新记录(具有正确的旧值)并将外键设置为null
而不是更新现有记录:
[sqlalchemy.engine.base.Engine][Dummy-2] UPDATE location SET event_id=? WHERE location.id = ?
[sqlalchemy.engine.base.Engine][Dummy-2] (None, 1)
[sqlalchemy.engine.base.Engine][Dummy-2] INSERT INTO location (name, event_id) VALUES (?, ?)
[sqlalchemy.engine.base.Engine][Dummy-2] (u'loc2', 1)
[sqlalchemy.engine.base.Engine][Dummy-2] COMMIT
型号:
class Event(Base):
__tablename__ = 'event'
id = Column(Integer, primary_key=True)
name = Column(Unicode(255), nullable=False)
class Location(Base):
__tablename__ = 'location'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(Unicode(255), nullable=True)
event_id = Column(Integer, ForeignKey(Event.id))
event = relationship(
Event,
backref='locations' # the event needs to have this
)
查看:
class LocationForm(ModelForm):
class Meta:
model = Location
class EventForm(ModelForm):
class Meta:
model = Event
locations = ModelFieldList(ModelFormField(LocationForm))
class UserButton(Form):
save_btn = wtforms.SubmitField('Save Data')
@view_config(route_name='ev', renderer='templates/ev.pt')
def ev(request):
one = DBSession.query(Event).first()
ev = EventForm(obj=one)
ub = UserButton()
if request.method == 'POST':
new_uf = EventForm(request.POST)
new_uf.populate_obj(one)
transaction.commit()
return {'ev':ev, 'ub':ub}
表格:
<form method="POST">
<ul id="locations"><li><label for="locations-0">Locations-0</label> <table id="locations-0"><tr><th><label for="locations-0-name">name</label></th><td><input id="locations-0-name" name="locations-0-name" type="text" value="location1"></td></tr></table></li></ul>
<br>
<input id="name" name="name" required type="text" value="event1">
<br>
<input id="save_btn" name="save_btn" type="submit" value="Save Data">
</form>
我在DB中的location
表中看到了这一点:
id name event_id
1 location1 <null>
2 loc2 1
我该如何解决?也就是说,我想更新Event
的{{1}}对象,而不是创建一个新对象? (即使使用相同的数据)。
答案 0 :(得分:2)
你必须让Form
知道它是一个现有的对象:
obj = MyModel.query.get(1)
form = MyForm(obj=obj)
form.populate_obj(obj)
form.validate()