9b689af114527d1c2623dcdc76fc2bd3d21ff7a2
[django-historique.git] / django_historique / models.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 from django.db import models
4 from django.db.models.base import ModelBase
5 from django.db import connection, transaction
6 from copy import deepcopy
7 import datetime
8
9
10 def log_instance (i, prefix=""):
11 "Pour debug, affichage d'un objet et de ses attributs"
12 print prefix, i, i.__class__.__name__
13 for f in i._meta.fields:
14 print prefix, " ", f.name, f.__class__.__name__
15
16 class History (models.Model):
17 "Classe abstraite de base pour l'historique"
18 history_datetime = models.DateTimeField(default=datetime.datetime.now)
19 history_objectid = models.PositiveIntegerField()
20 history_revision = models.PositiveIntegerField()
21 history_comment = models.CharField(max_length=1024, default="")
22
23 def save_log (self, instance):
24 "Enregistrement de l'instance courante avant l'ecriture de la nouvelle"
25 if instance.id:
26 iClass = instance.__class__
27 hClass = self.__class__
28
29 instance = iClass.objects.get(id = instance.id)
30 self.history_objectid = instance.id
31 self.history_comment = "pre_save history item <%s>" \
32 % (repr(instance))
33 self.history_revision = hClass.objects.filter(history_objectid=instance.id).count()+1
34
35 for field in instance._meta.fields:
36 if field.__class__.__name__ != 'AutoField':
37 if getattr(field, 'unique', False):
38 field._unique = False
39 setattr(self, field.name, getattr(instance, field.name))
40
41 #log_instance (instance, "I")
42 #log_instance (self, "S")
43
44 #self.save ()
45 super (History, self).save ()
46
47 def save (self):
48 pass
49
50 def diff_with (self, instance, ignore = None, \
51 choice_value = True, verbose_names = True):
52 ignored = ["history_datetime", "history_objectid",
53 "history_revision", "history_comment"]
54 if ignore:
55 ignored.extend (ignore)
56 diffs = []
57 for field in instance._meta.fields:
58 if field.__class__.__name__ != 'AutoField' \
59 and field.name not in ignored:
60 try:
61 hvalue = getattr (self, field.name, "")
62 except:
63 pass
64 if hvalue is None:
65 hvalue = ""
66
67 try:
68 ivalue = getattr (instance, field.name, "")
69 except:
70 ivalue = ""
71 if ivalue is None:
72 ivalue = ""
73
74 if ivalue != hvalue:
75 if choice_value and len (field.choices) > 0:
76 for pair in field.choices:
77 if ivalue == pair[0]: ivalue = pair[1]
78 if hvalue == pair[0]: hvalue = pair[1]
79
80 name = field.name
81 if verbose_names:
82 name = field.verbose_name
83
84 diffs.append({"name": name, \
85 "previous": hvalue, \
86 "updated": ivalue, \
87 "date": getattr(self, 'history_datetime')})
88 return diffs
89
90 class Meta:
91 abstract = True
92
93