Ajout django_history_tables
[cyril.git] / Apps / django_history_tables / models.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from django.db import models
5 from django.db.models.base import ModelBase
6 from django.utils.translation import ugettext_lazy as _
7 from copy import deepcopy
8
9 import copy
10 import datetime
11
12 __all__ = ["HistoryModelBase", "HistoryModel", "history_save"]
13
14
15 class HistoryModelBase(ModelBase):
16 def __new__(cls, name, bases, dct):
17 new_class = ModelBase.__new__(cls, name, bases, dct)
18 if 'History' in dct:
19 history_model = dct['History'].model
20 for field in history_model._meta.fields:
21 if field.__class__.__name__ != 'AutoField':
22 _field = deepcopy(field)
23 if getattr(_field, 'unique', False):
24 _field._unique = False
25 rel = getattr(_field, 'rel', None)
26 if rel and rel.related_name:
27 rel.related_name = rel.related_name + "history"
28 new_class.add_to_class(_field.name, _field)
29 for mm in history_model._meta.many_to_many:
30 _mm = deepcopy(mm)
31 if getattr(_mm, 'unique', False):
32 _mm._unique = False
33 rel= getattr(_mm, 'rel', None)
34 if rel and rel.related_name:
35 rel.related_name = rel.related_name + "history"
36 if rel and rel.through:
37 rel.through = rel.through + "History"
38 else:
39 new_class.add_to_class(_mm.name, _mm)
40 return new_class
41
42 class HistoryModel(models.Model):
43 __metaclass__ = HistoryModelBase
44
45 history_datetime = models.DateTimeField(default=datetime.datetime.now)
46 history_objectid = models.PositiveIntegerField()
47 history_revision = models.PositiveIntegerField()
48 history_comment = models.CharField(max_length=1024, default="")
49
50 class Meta:
51 abstract = True
52
53 def history_save(sender, instance, signal, history_model, *args, **kwargs):
54 if not instance.id:
55 # initial save, don't have to do anything :)
56 return
57 orginal = sender.objects.get(pk=instance.id)
58 history_obj = history_model()
59
60 history_obj.history_objectid = orginal.id
61 history_obj.history_revision = history_model.objects. \
62 filter(history_objectid = orginal.id).count() + 1
63 history_obj.history_comment = "pre_save history item <%s>" % \
64 (repr(orginal))
65
66 for field in orginal._meta.fields:
67 if field.__class__.__name__ == 'AutoField':
68 continue
69 setattr(history_obj, field.name, getattr(orginal, field.name))
70 history_obj.save()
71 for mm in orginal._meta.many_to_many:
72 setattr(history_obj, mm.name, getattr(orginal, mm.name).all())
73 history_obj.save()