from annoying decorators import signals from dumps models import CodeH

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from annoying.decorators import signals
from dumps.models import CodeHistory, Code
@signals.pre_save(sender=Code)
def history_save(sender, instance, **kwargs):
if not instance.id:
# initial save, don't have to do anything :)
return
# lookup history model if exists, otherwise return (quick exit if history is not managed)
history_model = CodeHistory # right now this is a quick shortcut to our test
# lookup orginal unchanged object
orginal = sender.objects.get(pk=instance.id)
# copy orginal object into history
history_obj = history_model()
history_obj.history_objectid = orginal.id
history_obj.history_revision = history_model.objects.filter(history_objectid=orginal.id).count()+1
history_obj.history_comment = "pre_save history item <%s>" % (repr(orginal))
for field in orginal._meta.fields:
if 'AutoField' == field.__class__.__name__:
continue
setattr(history_obj, field.name, getattr(orginal, field.name))
history_obj.save()
for mm in orginal._meta.many_to_many:
setattr(history_obj, mm.name, getattr(orginal, mm.name).all())
history_obj.save()