What would be the most elegant\efficient way to reset all fields of a certain model instance back to their defaults?
Wouldn't that work only in a subset of situations? For instance, would it work for fields not marked with blank=True and null=True?
Jonathan
2010-07-12 15:29:45
Database inserts or updates of NULL are changed to the field's default value.
Ignacio Vazquez-Abrams
2010-07-12 15:43:39
A:
After you've made changes to that instance but before you've "saved" it, I assume? I think you'll probably need to re-retrieve it from the database... I don't think that Django model instances keep a "history" of changes that have been made to an instance.
Matthew J Morrison
2010-07-12 15:18:31
A:
I once did it this way. No better way I could think of.
from django.db.models.fields import NOT_PROVIDED
for f in instance._meta.fields:
if f.default <> NOT_PROVIDED:
setattr(instance, f.name, f.default)
# treatment of None values, in your words, to handle fields not marked with null=True
...
...
# treatment ends
instance.save()
Note: In my case all the fields, did have default value.
Hope it'll help. Happy Coding.
simplyharsh
2010-07-12 16:33:05