跳转到主要内容

Marty Alchin的HistoricalRecords来自ProDjango书籍。

项目描述

这是来自Marty Alchin的Pro Django书籍的内容。

设置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,您将看到它自动为您附加的任何模型创建一个Historical版本。

(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'
>>>

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

django-historicalrecords-1.1.tar.gz (5.2 kB 查看散列)

上传时间:

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面