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() )
- Reorder model objects in django admin panel
- Django Rest Framework nested serializer not showing related data
- How to build a secure Django single signon between different sites?
- Request input from django custom command?
- Populating a SQLite3 database from a .txt file with Python
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).
- Appropriate choice of authentication class for python REST API used by web app
- Using annotate or extra to add field of foreignkey to queryset ? (equivalent of SQL "AS" ?)
- Difference between JSONParser and JSONRenderer
- Tracking changes to all models in Django
- Django : Change default value for an extended model class
- Django: query all items that have a foreign key point to them
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.
- Disable pylint warning E1101 when using enums
- Django – ModelForm Create or Update?
- How to validate/clean() a unique=True field without using a ModelForm?
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()
- Library not loaded: @rpath/libmysqlclient.21.dylib Reason: image not found Django migrate error using mysqlclient DB driver and MySQL 8 with macOS
- How can I make a fixture out of QuerySet in django?
- Django sekizai {% addtoblock %} tag is not working properly
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__)
- Protocol error, got "H" as reply type byte
- How do I serve media files in a local Django environment?