views:

38

answers:

3

What would be the most elegant\efficient way to reset all fields of a certain model instance back to their defaults?

+3  A: 

Assign None to the fields, and save.

Ignacio Vazquez-Abrams
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
Database inserts or updates of NULL are changed to the field's default value.
Ignacio Vazquez-Abrams
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
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