Do not emit post save on model
I am building an app in django and I have decided to add historical records to keep track of changes to data in a model. I am using django-simple-history to achieve this. This package apparently saves a history record on the post_save signal.
I would like to be able to save objects sometimes without saving a history, like when I run some background queries and need to save data. My questions is, "can I prevent a model from emitting a post save signal"
I currently have a workaround for this. I have a boolean variable that I set to True when I want to show a history for that record. But this does not prevent the historical record from 开发者_Go百科being created.
THank you.
I'm not so hot on signals, but I think you should alter the signal handler, rather than stop a signal from being emitted. What if you need to do some other, unrelated stuff after saving a model?
Try patching create_historical_record() in django-simple-history/simple_history/models.py, putting the following snippet at the top:
create_historical_record(self, instance, type):
if hasattr(instance, 'save_history') and not instance.save_history:
return
#rest of method
You could also try temporarily disconnecting the history tracker from your model instance, then reconnecting it after, but I'm not sure where you'd do that. It would probably be more error-prone, too.
Oh yeah, you could also subclass HistoricalRecords:
class OptHistoricalRecords(HistoricalRecords):
def create_historical_record(self, instance, type):
if hasattr(instance, 'save_history') and not instance.save_history:
return
else:
super(OptHistoricalRecords,self).create_historical_record(instance,type)
There is a method that gets contributed to the model with contribute_to_class
, its name is save_without_historical_record
:
obj.some_field = new_value
obj.save_without_historical_record()
...
# now create a record.
obj.save()
精彩评论