马蒂·阿尔钦在普罗詹戈书中的历史记录。
django-historicalrecords-unleashed的Python项目详细描述
这是马蒂·阿尔钦的书。
设置virtualenv
$ virtualenv --no-site-packages ve $ source ve/bin/activate (ve)$ pip install -r requirements.pip
或者从pypi安装
$ pip install django-historicalrecords
导入historicalrecords并将其附加到您的模型,就像您将其作为自定义django管理器一样。
from django.db import models from history.models import HistoricalRecords class TestModel(models.Model): """A model for testing""" boolean = models.BooleanField(default=True) characters = models.CharField(blank=True, max_length=100) history = HistoricalRecords() class Admin: list_display = ('',) search_fields = ('',) def __unicode__(self): return u"TestModel"
如果运行manage.py syncdb您将看到它会自动创建您附加到的任何模型的历史版本。
(ve)$ ./manage.py syncdb Creating table auth_permission ... // snip // ... Creating table example_app_historicaltestmodel <- HistoricalTestModel! Creating table example_app_testmodel ... // snip // ...
historicalrecords克隆它附加到的模型,并添加一些额外的字段,允许您跟踪所做更改的类型、保存更改时的时间戳,以及在更改时返回原始对象的描述符。
(ve)$ ./manage.py shell >>> from example_app.models import TestModel >>> tm = TestModel.objects.create(boolean=True,characters="abc") >>> tm.history.count() 1 >>> most_recent = tm.history.most_recent() >>> most_recent.boolean True >>> most_recent.characters u'abc' >>> tm.boolean = False >>> tm.characters = "def" >>> tm.save() >>> tm.history.count() 2 >>> tm.history.all() [<HistoricalTestModel: TestModel as of 2010-09-10 03:29:59.424761>, <HistoricalTestModel: TestModel as of 2010-09-10 03:28:31.358548>] >>> from datetime import datetime >>> timestamp = datetime(2010,9,10,3,28,31,358548) >>> old_version = tm.history.as_of(timestamp) >>> old_version.boolean True >>> tm.boolean False >>> old_version.characters u'abc' >>> tm.characters 'def' >>>