What would be the most elegant\efficient way to reset all fields of a certain model instance back to their defaults?
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.
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() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With