|
| 1 | +import copy |
| 2 | +import datetime |
| 3 | + |
| 4 | +from django.db import models |
| 5 | + |
| 6 | +from chapter11.current_user import models as current_user |
| 7 | +from chapter11.history import manager |
| 8 | + |
| 9 | +class HistoricalRecords(object): |
| 10 | + def contribute_to_class(self, cls, name): |
| 11 | + self.manager_name = name |
| 12 | + models.signals.class_prepared.connect(self.finalize, sender=cls) |
| 13 | + |
| 14 | + def finalize(self, sender, **kwargs): |
| 15 | + history_model = self.create_history_model(sender) |
| 16 | + |
| 17 | + # The HistoricalRecords object will be discarded, |
| 18 | + # so the signal handlers can't use weak references. |
| 19 | + models.signals.post_save.connect(self.post_save, sender=sender, |
| 20 | + weak=False) |
| 21 | + models.signals.post_delete.connect(self.post_delete, sender=sender, |
| 22 | + weak=False) |
| 23 | + |
| 24 | + descriptor = manager.HistoryDescriptor(history_model) |
| 25 | + setattr(sender, self.manager_name, descriptor) |
| 26 | + |
| 27 | + def create_history_model(self, model): |
| 28 | + """ |
| 29 | + Creates a historical model to associate with the model provided. |
| 30 | + """ |
| 31 | + attrs = self.copy_fields(model) |
| 32 | + attrs.update(self.get_extra_fields(model)) |
| 33 | + attrs.update(Meta=type('Meta', (), self.get_meta_options(model))) |
| 34 | + name = 'Historical%s' % model._meta.object_name |
| 35 | + return type(name, (models.Model,), attrs) |
| 36 | + |
| 37 | + def copy_fields(self, model): |
| 38 | + """ |
| 39 | + Creates copies of the model's original fields, returning |
| 40 | + a dictionary mapping field name to copied field object. |
| 41 | + """ |
| 42 | + # Though not strictly a field, this attribute |
| 43 | + # is required for a model to function properly. |
| 44 | + fields = {'__module__': model.__module__} |
| 45 | + |
| 46 | + for field in model._meta.fields: |
| 47 | + field = copy.copy(field) |
| 48 | + |
| 49 | + if isinstance(field, models.AutoField): |
| 50 | + # The historical model gets its own AutoField, so any |
| 51 | + # existing one must be replaced with an IntegerField. |
| 52 | + field.__class__ = models.IntegerField |
| 53 | + |
| 54 | + if field.primary_key or field.unique: |
| 55 | + # Unique fields can no longer be guaranteed unique, |
| 56 | + # but they should still be indexed for faster lookups. |
| 57 | + field.primary_key = False |
| 58 | + field._unique = False |
| 59 | + field.db_index = True |
| 60 | + fields[field.name] = field |
| 61 | + |
| 62 | + return fields |
| 63 | + |
| 64 | + def get_extra_fields(self, model): |
| 65 | + """ |
| 66 | + Returns a dictionary of fields that will be added to the historical |
| 67 | + record model, in addition to the ones returned by copy_fields below. |
| 68 | + """ |
| 69 | + rel_nm = '_%s_history' % model._meta.object_name.lower() |
| 70 | + return { |
| 71 | + 'history_id': models.AutoField(primary_key=True), |
| 72 | + 'history_date': models.DateTimeField(default=datetime.datetime.now), |
| 73 | + 'history_user': current_user.CurrentUserField(related_name=rel_nm), |
| 74 | + 'history_type': models.CharField(max_length=1, choices=( |
| 75 | + ('+', 'Created'), |
| 76 | + ('~', 'Changed'), |
| 77 | + ('-', 'Deleted'), |
| 78 | + )), |
| 79 | + 'history_object': HistoricalObjectDescriptor(model), |
| 80 | + '__unicode__': lambda self: u'%s as of %s' % (self.history_object, |
| 81 | + self.history_date) |
| 82 | + } |
| 83 | + |
| 84 | + def get_meta_options(self, model): |
| 85 | + """ |
| 86 | + Returns a dictionary of fields that will be added to |
| 87 | + the Meta inner class of the historical record model. |
| 88 | + """ |
| 89 | + return { |
| 90 | + 'ordering': ('-history_date',), |
| 91 | + } |
| 92 | + |
| 93 | + def post_save(self, instance, created, **kwargs): |
| 94 | + self.create_historical_record(instance, created and '+' or '~') |
| 95 | + |
| 96 | + def post_delete(self, instance, **kwargs): |
| 97 | + self.create_historical_record(instance, '-') |
| 98 | + |
| 99 | + def create_historical_record(self, instance, type): |
| 100 | + manager = getattr(instance, self.manager_name) |
| 101 | + attrs = {} |
| 102 | + for field in instance._meta.fields: |
| 103 | + attrs[field.attname] = getattr(instance, field.attname) |
| 104 | + manager.create(history_type=type, **attrs) |
| 105 | + |
| 106 | +class HistoricalObjectDescriptor(object): |
| 107 | + def __init__(self, model): |
| 108 | + self.model = model |
| 109 | + |
| 110 | + def __get__(self, instance, owner): |
| 111 | + values = (getattr(instance, f.attname) for f in self.model._meta.fields) |
| 112 | + return self.model(*values) |
0 commit comments