Ajout setup.py
[django-historique.git] / django_historique / models.py
CommitLineData
6ca2f470 1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3from django.db import models
4from django.db.models.base import ModelBase
5from django.db import connection, transaction
6from copy import deepcopy
7import datetime
8
9
6ca2f470 10def log_instance (i, prefix=""):
6a680ab4 11 "Pour debug, affichage d'un objet et de ses attributs"
6ca2f470 12 print prefix, i, i.__class__.__name__
13 for f in i._meta.fields:
14 print prefix, " ", f.name, f.__class__.__name__
15
16class History (models.Model):
6a680ab4 17 "Classe abstraite de base pour l'historique"
6ca2f470 18 history_datetime = models.DateTimeField(default=datetime.datetime.now)
6a680ab4 19 history_objectid = models.PositiveIntegerField()
20 history_revision = models.PositiveIntegerField()
6ca2f470 21 history_comment = models.CharField(max_length=1024, default="")
22
23 def save_log (self, instance):
6a680ab4 24 "Enregistrement de l'instance courante avant l'ecriture de la nouvelle"
fab77961 25 if instance.id:
26 iClass = instance.__class__
27 hClass = self.__class__
6a680ab4 28
fab77961 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))
6a680ab4 40
fab77961 41 #log_instance (instance, "I")
42 #log_instance (self, "S")
6a680ab4 43
fab77961 44 #self.save ()
45 super (History, self).save ()
0b8256dc 46
47 def save (self):
48 pass
6ca2f470 49
fab77961 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 hvalue = getattr (self, field.name, "")
61 if hvalue is None:
62 hvalue = ""
63 ivalue = getattr (instance, field.name, "")
64 if ivalue is None:
65 ivalue = ""
66 if ivalue != hvalue:
67 if choice_value and len (field.choices) > 0:
68 for pair in field.choices:
69 if ivalue == pair[0]: ivalue = pair[1]
70 if hvalue == pair[0]: hvalue = pair[1]
71
72 name = field.name
73 if verbose_names:
74 name = field.verbose_name
75
76 diffs.append({"name": name, \
77 "previous": hvalue, \
78 "updated": ivalue, \
79 "date": getattr(self, 'history_datetime')})
80 return diffs
81
6ca2f470 82 class Meta:
83 abstract = True
84
85