Package: django-diffs
Django DiffsDjango diffs allows models to be registered to cache it’s changes (or diffs) over a fixed time period.The diffs are stored in redis using a SortedSet and accessed via a manager-like object on the registered django model class.It’s compatible with Python 2/3 and Django 1.8 and above. It requires an available redis server.Table of ContentsGetting StartedConfigurationPruning DiffsCustom SerializationRelated modelsHow does it Work?Models are registered with the@diffs.registerdecorator and their changes are serialized and saved to redis on signals.
The decorator installs django-dirtyfields to the model on registration to get the changed fields of the model instance.Changes can be accessed via thediffsmanager on the registered model. The diffs manager returns a list ofDiffobjects that have properties ofdata,created, andtimestamp.The manager can be accessed via the class likeQuestion.diffsor like a related manager on the instanceinstance.diffs.Here’s a quick example.# models.pyimportdiffs@diffs.registerclassQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')question=Question.objects.create(question_text='What is life?')question.question_text='What is python?'question.save()fordiffinquestion.diffs:print(diff.timestamp)print(diff.data)print(diff.created)diffs=Question.diffs.get_by_object_id(question.id)Why?You need to cache the changes to a single django model or collection of models for a fixed time period.Tracking the changes prevents clients from having to re-request all of the model data which is assumed to be costly.Getting StartedAdddjango-diffstorequirements.txtpipinstalldjango-diffsAdddiffstoINSTALLED_APPSINSTALLED_APPS=('diffs',)Register a Model# models.pyimportdiffs@diffs.registerclassQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')That’s it! Changes will now be tracked automatically for this model.ConfigurationDjango-diffs can be configured viadjango.conf.settings. Below is the default configuration# settings.pyDIFFS_SETTINGS={'redis':{'host':'localhost','port':6379,'db':0,},'max_element_age':60*60,'use_transactions':True,'test_mode':False}The following keys are supported forDIFFS_SETTINGSredis– A dictionary with the keyshost,portanddbfor details of the redis server.max_element_age– Defines the number of seconds a single diff should be allowed to live. This is used in the pruning script
to remove old elements from the set.use_transactions– Boolean to configure django-diffs using Django’sconnection.on_commitcallback registry. When enabled
django-diffs will defer persistence toon_commit.test_mode– Boolean to configure using test mode. Test mode usesfake_redisinstead of realredisso a server isn’t required.
Use this mode when running your unittests.Pruning DiffsBy default redis only allows you to set an expire on an entire key. You cannot set an expiry per element in a set or sorted set.To work around this django-diffs sets the current unix timestamp as the SortedSet element score. Items can then be easily removed
using the redis commandZREMRANGEBYSCORE.All of this has been handled for you in the custom management commandprune_diffs. Run this on a cron schedule to keep your
cache up to date.pythonmanage.pyprune_diffsCustom SerializationBy default django-diffs usesdjango.core.serializersmodule to serialize the diff to json.To use your own custom serialization format just implement theserialize_diffmethod
on your model. It will be passed the list ofdirty_fieldsand thecreatedkwarg.# models.pyimportdiffs@diffs.registerclassQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')defserialize_diff(self,dirty_fields,created=False):return{'fields':dirty_fields}question=Question.objects.create(question_text='What will happen?')Question.diffs.get_by_object_id(question.id)[-1].data# {'fields': ['question_name']}Related modelsSometimes you want to track changes on a collection of related models.
These could be individual items part of a larger Report object.Django-diffs allows you to set a parent objects by implementingget_diff_parenton
the child model. It must return a model instance with an id defined.# models.pyimportdiffs@diffs.registerclassQuestion(models.Model):question_text=models.CharField(max_length=200)pub_date=models.DateTimeField('date published')@diffs.registerclassChoice(models.Model):question=models.ForeignKey(Question,on_delete=models.CASCADE)choice_text=models.CharField(max_length=200)votes=models.IntegerField(default=0)defget_diff_parent(self):# save the db lookupreturnQuestion(id=self.question_id)question=Question.objects.create(question_text='What will happen?')choice=Choice.objects.create(choice_text='Nothing',question=question)choice.choice_text='Something'choice.save()# returns diffs for question and it's choiceslen(question.diffs)# 3