问题
I have some Flask-SQLAlchemy models and Flask-WTF forms generated with wtforms_alchemy to represent them. I implemented a method on each model to update its attributes from a form's data. For each new model and field I have to update these methods, which is annoying. Is there a way to make this more automatic, or a a feature in the libraries I'm using that I'm missing?
def edit_car(car_id):
form = CarForm(request.form)
if form.is_valid():
car = Car.query.get_or_404(car_id)
car.from_form(form) # Update car fields
...
# save car in database ...
class Car(db.Model):
color = db.Column(db.String(10))
...
def from_form(self, form):
self.color = form.color.data
... # all other fields
回答1:
Use the form's populate_obj method to fill in the model. It sets an attribute of the same name as each field.
form.populate_obj(car)
db.session.commit()
If the simple "set attribute by field name" behavior isn't appropriate for a given model/form pair (although it should be in your case), you can override the method.
class SpecialCarForm(FlaskForm):
...
def populate_obj(obj):
# mess with data, set extra fields, etc.
# potentially call super after
super().populate_obj(obj)
来源:https://stackoverflow.com/questions/46609908/update-model-with-wtforms-form-data