Skip to main content

Django Diffs

https://travis-ci.org/linuxlewis/django-diffs.svg?branch=master

Django diffs allows models to be registered to cache it’s changes (or diffs) over a fixed time period.

The diffs are stored in redis using a SortedSet and accessed via a manager-like object on the registered django model class.

It’s compatible with Python 2/3 and Django 1.8 and above. It requires an available redis server.

Table of Contents

How does it Work?

Models are registered with the @diffs.register decorator and their changes are serialized and saved to redis on signals. The decorator installs django-dirtyfields to the model on registration to get the changed fields of the model instance.

Changes can be accessed via the diffs manager on the registered model. The diffs manager returns a list of Diff objects that have properties of data, created, and timestamp.

The manager can be accessed via the class like Question.diffs or like a related manager on the instance instance.diffs.

Here’s a quick example.

# models.py

import diffs

@diffs.register
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

question = Question.objects.create(question_text='What is life?')

question.question_text = 'What is python?'
question.save()

for diff in question.diffs:
    print(diff.timestamp)
    print(diff.data)
    print(diff.created)

diffs = Question.diffs.get_by_object_id(question.id)

Why?

You need to cache the changes to a single django model or collection of models for a fixed time period.

Tracking the changes prevents clients from having to re-request all of the model data which is assumed to be costly.

Getting Started

  • Add django-diffs to requirements.txt

pip install django-diffs
  • Add diffs to INSTALLED_APPS

INSTALLED_APPS = (
    'diffs',
)
  • Register a Model

# models.py

import diffs

@diffs.register
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

That’s it! Changes will now be tracked automatically for this model.

Configuration

Django-diffs can be configured via django.conf.settings. Below is the default configuration

# settings.py

DIFFS_SETTINGS = {
    'redis': {
        'host': 'localhost',
        'port': 6379,
        'db': 0,
    },
    'max_element_age': 60*60,
    'use_transactions': True,
    'test_mode': False
}

The following keys are supported for DIFFS_SETTINGS

redis – A dictionary with the keys host, port and db for details of the redis server.

max_element_age – Defines the number of seconds a single diff should be allowed to live. This is used in the pruning script to remove old elements from the set.

use_transactions – Boolean to configure django-diffs using Django’s connection.on_commit callback registry. When enabled django-diffs will defer persistence to on_commit.

test_mode – Boolean to configure using test mode. Test mode uses fake_redis instead of real redis so a server isn’t required. Use this mode when running your unittests.

Pruning Diffs

By default redis only allows you to set an expire on an entire key. You cannot set an expiry per element in a set or sorted set.

To work around this django-diffs sets the current unix timestamp as the SortedSet element score. Items can then be easily removed using the redis command ZREMRANGEBYSCORE.

All of this has been handled for you in the custom management command prune_diffs. Run this on a cron schedule to keep your cache up to date.

python manage.py prune_diffs

Custom Serialization

By default django-diffs uses django.core.serializers module to serialize the diff to json.

To use your own custom serialization format just implement the serialize_diff method on your model. It will be passed the list of dirty_fields and the created kwarg.

# models.py

import diffs

@diffs.register
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def serialize_diff(self, dirty_fields, created=False):
        return {'fields': dirty_fields}

question = Question.objects.create(question_text='What will happen?')

Question.diffs.get_by_object_id(question.id)[-1].data
# {'fields': ['question_name']}

Metadata

Release files for django-diffs 0.1.16

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-diffs 0.1.16
File Size Uploaded
django-diffs-0.1.16.tar.gz 7.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-diffs 0.1.16
File Interpreter ABI Platform
django_diffs-0.1.16-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 19.7 kB

Release files / django-diffs-0.1.16.tar.gz

Download URL django-diffs-0.1.16.tar.gz
Size 7.6 kB
Tags Source
SHA-256 checksum
How to use checksums
bd6ac5f643ea3ca731cc753185c49380d59641d395dee6f6e36a2f5330b706fb
BLAKE2b-256 checksum
How to use checksums
20778f92e42120f64272e5ba43ade096b517b0ec0afc56e7a1fa23a67db17180
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / django_diffs-0.1.16-py2.py3-none-any.whl

Download URL django_diffs-0.1.16-py2.py3-none-any.whl
Size 12.1 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
a2f399c21e249f9e3657c51ea3202e81947565e7dfc088c6077381973e23d899
BLAKE2b-256 checksum
How to use checksums
0fd0b4db96626e1282abc609615232be7cd85935335e6e233632cb98d8bc0536
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release history Release notifications | RSS feed

This release

0.1.16 This release

2 release files

0.1.15

2 release files

0.1.14

2 release files

0.1.13

2 release files

0.1.12

2 release files

0.1.10

2 release files

0.1.9

2 release files

0.1.8

1 release file

0.1.7

2 release files

0.1.6

1 release file

0.1.5

1 release file

0.1.4

1 release file

0.1.3

1 release file

0.1.2

1 release file

0.1.1

1 release file

0.1.0

1 release file

0.0.2

1 release file

0.0.1

3 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page