# -*- coding: utf-8 -*-# http://djangosnippets.org/snippets/2672/# myapp/management/commands/reversion_clean.pyu'''If you use this pattern to track changes in the auth user table: from django.contrib.auth.models import User from reversion.helpers import patch_admin patch_admin(User)you can't see important changes, since a version is created for everylogin if a user. If you want to get rid of changes which only changeunimportant stuff you can use this middleware.Edit your settings. Example:REVERSION_CLEAN={ 'django.contrib.auth': {'User': ['last_login']}, }Usage: manage.py reversion_clean'''importloggingfromdjango.confimportsettingsfromdjango.core.management.baseimportNoArgsCommand,CommandErrorfromdjango.utilsimportimportlibfromdjango.contrib.contenttypes.modelsimportContentTypefromreversion.modelsimportVersionclassCommand(NoArgsCommand):help="Clean unimportant changes in reversion history. Example: settings.py: REVERSION_CLEAN={'django.contrib.auth': {'User': ['last_login']}}"requires_model_validation=Falsedefhandle_noargs(self,**options):rootLogger=logging.getLogger('')rootLogger.setLevel(logging.INFO)ignores=getattr(settings,'REVERSION_CLEAN',None)ifnotignores:raiseCommandError('Error: settings.REVERSION_CLEAN is not set or empty.')empty_count=0only_ignore_count=0ok_count=0layout_count=0forapp,modelsinignores.items():import_str='%s.models'%appmodul=importlib.import_module(import_str)formodel,ignore_changes_attrsinmodels.items():model_class=getattr(modul,model)ct=ContentType.objects.get_for_model(model_class)last=NoneforversioninVersion.objects.filter(content_type=ct).order_by('object_id','id'):iflastisNone:last=version.get_field_dict()continuethis=version.get_field_dict()ifset(this.keys())-set(last.keys()):layout_count+=1continue# DB Layout has changed. Don't deletediff=dict()for(this_key,this_value),(last_key,last_value)inzip(sorted(this.items()),sorted(last.items())):assertthis_key==last_keyifthis_value==last_value:continuediff[this_key]=(this_value,last_value)ifnotdiff:logging.info('no changes in Version %s'%version)version.delete()empty_count+=1continueifset(diff.keys()).issubset(ignore_changes_attrs):logging.info('only changes to ignore: %s'%diff)version.delete()only_ignore_count+=1continueok_count+=1logging.info('Empty version: %s (del) Only ignore columns changed: %s (del) DB-Layout changed: %s (no-del) unchanged: %s (no-del)'%(empty_count,only_ignore_count,layout_count,ok_count))