[Fixed]-Django – How to reset model fields to their default value?

8👍

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.

4👍

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() )

2👍

This method is mainly applicable for resetting a single value to a default, but can be adapted. It resets the rego_update property for all my Event objects.

Event.objects.all().update(rego_update=Event().rego_update)

Alternatively, to apply it individually (i.e. to trigger custom save methods):

default = Event().rego_update  # Hack to fetch the default
for event in Event.objects.all():
    event.rego_update = default
    event.save()

To adapt this to reset all values for a single instance, you could manually reset each value with a default.

Alternatively, you could loop through the attributes similar to other answers here, but this will have issues with fields that have no default (or cannot be edited).

1👍

Assign None to the fields, and save.

0👍

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.

0👍

Assign None to all fields that are not nullable, by checking the .null field attribute:

for name, value in {f.name: None for f in self._meta.fields if f.null}:
    setattr(instance, name, value)
instance.save()

0👍

You can use self.your_field =self.__class__._meta.get_field('your_field').default.

Please note you should wrap this into a try/except while depending on your django’s version get_field might get some other name

0👍

Another solution would be to create a blank model instance and then update the current one with it, like this:

def reset(self):
    new_instance = type(self)()
    self.__dict__.update(new_instance.__dict__)

or if you want to keep the model id:

def reset(self):
    new_instance = type(self)(id=self.id)
    self.__dict__.update(new_instance.__dict__)

Leave a comment