Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to reset model fields to their default value?

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

like image 551
Jonathan Livni Avatar asked Jul 12 '10 15:07

Jonathan Livni


2 Answers

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.

like image 83
simplyharsh Avatar answered Sep 23 '22 16:09

simplyharsh


def reset( self, fields=[], exclude=[] ):

    fields = fields or filter( lambda x: x.name in fields, self._meta.fields )
    exclude.append( 'id' )        

    for f in filter( lambda x: x.name not in exclude, fields ):
        if getattr( f, 'auto_now_add', False ):
            continue

        if f.blank or f.has_default():
            setattr( self, f.name, f.get_default() )
like image 38
Pawel Furmaniak Avatar answered Sep 25 '22 16:09

Pawel Furmaniak