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