使用模型表格时:
>>> honest_man.name
u'Abe Lincoln'
>>> form = PersonForm({'name': u'Barack'}, instance=honest_man)
>>> if form.is_valid():
... print('Yay!')
... bankster = form.save()
... else:
... print('Uh Oh :(')
...
Uh Oh :(
>>> honest_man.name # So, we'll just check to be sure nothing changed
u'Barack'
>>> # Oh no, our instance has been corrupted. Now I have to query for it to get
>>> # a clean version without the changes the form made.
>>> honest_man = Person.objects.get(name=u'Abe Lincoln')
>>> # Wasted query because I still need the instance
有没有办法避免这种情况(我正在使用Django 1.3)?
答案 0 :(得分:1)
不,由于模型验证,这在1.3中无法避免。清理表单字段后,ModelForm使用已清理的数据填充实例的字段,并调用instance.clean_fields()和instance.clean()方法。