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


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


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

        if f.blank or f.has_default():
            setattr( self, f.name, f.get_default() )


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.


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

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


Assign None to the fields, and save.


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.


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)


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


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

or if you want to keep the model id:

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

Leave a comment