django模型更改允许您跟踪模型实例更改。
django-model-changes的Python项目详细描述
django模型更改允许您跟踪模型实例的状态和更改:
快速启动
安装Django型号更改:
pip install django-model-changes
将“django_model_changes”添加到已安装的应用程序设置中,如下所示:
INSTALLED_APPS = ( ... 'django_model_changes', )
< > >将获取实例更改:
>>> user = User() >>> user.name = 'Foo Bar' >>> user.save() >>> user.name 'I got a new name' >>> # Get current state >>> user.current_state() {'id': 1, 'name': 'I got a new name'} >>> # Get previous state (state after previous save/create/delete) >>> user.previous_state() {'id': 1, 'name': 'Foo Bar'} >>> # Get old state (state before previous save/create/delete) >>> user.old_state() {'id': None, 'name': ''} >>> # Get changes from the previous state to the current state >>> user.changes() {'name': ('Foo Bar', 'I got a new name')} >>> # Get changes from the old state to the current state >>> user.old_changes() {'id': (None, 1), 'name': ('', 'Foo Bar')} >>> # Check if the instance was persisted (saved) >>> user.was_persisted() False >>> # Check if the instance is persisted >>> user.is_persisted() True
收听更改:
>>> from django_model_changes import post_change
>>> def my_callback(sender, instance, **kwargs): >>> # Do something with previous and current state >>> instance.old_state() >>> instance.current_state()
>>> # There is also a convenience method to get >>> # an instance from the previous state >>> instance.old_instance()
>>> post_change.connect(my_callback, User)
>>> from django.db import models >>> from django_model_changes import ChangesMixin >>> class User(ChangesMixin, models.Model): >>> name = models.CharField(max_length=100)
概述
django模型更改允许您从 实例:
- 当前状态()
- 实例的当前状态。
- 上一个状态()
- 实例在创建、保存或删除 上次。
- 旧状态()
- 上一个_state(),即实例之前的状态 它是上次创建、保存或删除的。
它还提供了方便的方法来获取状态之间的更改:
- 更改()
- 从以前的状态更改为当前状态。
- 以前的更改()
- 从旧状态更改为以前的状态。
- 旧的更改()
- 从旧状态更改为当前状态。
以及以下方法来确定实例是否在 数据库:
- 被持久化了
- 实例是否保持其旧状态。
- 被持久化
- 实例是否保存在当前状态。
此示意图试图说明这些方法如何相互关联:
after create/save/delete after save/delete now | | | .-----------------------------------.----------------------------------. |\ |\ |\ | \ | \ | \ | old_state() | previous_state() | current_state() | | | |-----------------------------------|----------------------------------| | previous_changes() (prev - old) | changes() (cur - prev) | |-----------------------------------|----------------------------------| | old_changes() (cur - old) | .----------------------------------------------------------------------. \ \ \ \ was_persisted() is_persisted()
文档
请参阅changes.py中的文档字符串,或生成文档:
>>> pip install Sphinx >>> cd docs >>> make html Open build/html/index.html