DCM is a set of tools that helps you to keep your data in your Django Models consistent.

Overview

PyPI version fury.io PyPI pyversions PyPI - Django Version Code style: black

Django Consistency Model

DCM is a set of tools that helps you to keep your data in your Django Models consistent.

Django Consistency Model

Motivation

  • You have a lot of legacy and inconsistent data in your project and you need to clean it out
  • You want to monitor the broken data
  • You are looking for a very simple solution.

Quick Start

Install the package:

pip install django-consistency-model

Add new app into INSTALLED_APPS:

INSTALLED_APPS = (
    # ...
    "consistency_model",
)

Add your first validator using decorator consistency_validator:

from decimal import Decimal
from django.db import models
from consistency_model import consistency_validator

class Order(models.Model):
    total = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )
    refund = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )
    revenue = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )

    @consistency_validator
    def validate_revenue(self):
        assert self.revenue == self.total - self.refund, "revenue = total - refund"

Run command to check validators:

./manage.py consistency_model_check

What if I need to check more than one condition in one validator

The first thing you may think of is using more than one validator, and it is common to have more than one validator (for example, one validator per field).

Sometimes, you want to check more than one aspect in one validator or have a complex calculation you don't want to do for every validator.

For those cases, you may want to use function consistency_error. It shows the system an error without raising an exception, so one validator can generate more than one error.

= 0, "can't be negative" @consistency_validator def validate_revenue(self): if self.revenue < 0: consistency_error("can't be negative", "negative") if self.revenue != self.total - self.refund: consistency_error("revenue = total - refund", "formula")">
from decimal import Decimal

from django.db import models

from consistency_model import consistency_validator, consistency_error


class Order(models.Model):
    total = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )
    refund = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )
    revenue = models.DecimalField(
        default=Decimal("0.00"), decimal_places=2, max_digits=10
    )

    @consistency_validator
    def validate_total(self):
        assert self.total >= 0, "can't be negative"

    @consistency_validator
    def validate_revenue(self):
        if self.revenue < 0:
            consistency_error("can't be negative", "negative")

        if self.revenue != self.total - self.refund:
            consistency_error("revenue = total - refund", "formula")

As you can see, one validator (validate_revenue) checks two factors of the field revenue.

The function consistency_error has two arguments - message and name(optional). The name is a unique value for the validator and will be used in monitoring.

I don't want to check all of the data, but only one model instead.

When you add a new validator, you don't want to check all the data. You want to test only one validator instead.

Argument --filter can help you with that

./manage.py consistency_model_check --filter storeapp.Order.validate_revenue

Check only one model

./manage.py consistency_model_check --filter storeapp.Order

Check the model but excluding one validator. Argument --exclude excludes validator from validation circle.

./manage.py consistency_model_check --filter storeapp.Order --exclude storeapp.Order.validate_revenue

Check only one object. Using --object you can check a specific object in db.

./manage.py consistency_model_check --object storeapp.Order.56

You can combine --object with --filter and --exclude as well.

I want to monitor my DB on consistency constantly.

The idea of consistency monitoring is very simple. You add the command consistency_model_monitoring to your cron. The command checks DB and saves all of the errors in ConsistencyFail. Nothing is too complicated.

As the result, you can see all of the inconsistency errors in admin panel. Or you can connect pre_save signal to consistency_model.ConsistencyFail and send an email notification in case of any new inconsistency.

Monitoring configuration.

A typical situation is when you don't want to monitor all the data but only recently added/updated data. By default, the system checks only 10k recent IDs, but you have a lot of flexibility to change that with function register_consistency.

Let's take a look of how one can be used.

For model Order you want to check only 10 last ids.

from consistency_model import register_consistency
register_consistency(Order, limit=10)

register_consistency can be used as class decorator

from consistency_model import register_consistency

@register_consistency(limit=10)
class Order(models.Model):
    # ...

you can order not by id, but modified_on field

from consistency_model import register_consistency
register_consistency(Order, order_by='modified_on')

you can use a consistency checker class to overwrite the whole query for consistency check

from django.db import models

from consistency_model import register_consistency, ConsistencyChecker


class Order(models.Model):
    is_legacy = models.BooleanField(dafult=False)
    # ...


class OrderConsistencyChecker(ConsistencyChecker):
    limit = None # I don't want to have any limitation
    order_by = 'modified_on'

    def get_queryset(self):
        return self.cls.objects.filter(is_legacy=False)

register_consistency(Order, OrderConsistencyChecker)

Again, it is possible to be used as class decorator for any on both classes.

For Model:

from django.db import models

from consistency_model import register_consistency, ConsistencyChecker


class OrderConsistencyChecker(ConsistencyChecker):
    # ...

@register_consistency(OrderConsistencyChecker)
class Order(models.Model):
    is_legacy = models.BooleanField(dafult=False)
    # ...

For Checker:

from django.db import models

from consistency_model import register_consistency, ConsistencyChecker


class Order(models.Model):
    is_legacy = models.BooleanField(dafult=False)
    # ...


@register_consistency(Order)
class OrderConsistencyChecker(ConsistencyChecker):
    # ...

Settings

CONSISTENCY_DEFAULT_MONITORING_LIMIT (default: 10_000) - default limit rows per model

CONSISTENCY_DEFAULT_ORDER_BY (default: "-id") - defaul model ordering for monitoring

CONSISTENCY_DEFAULT_CHECKER (default: "consistency_model.tools.ConsistencyChecker") - default class for consistency monitoring

If you have pid package installed, one will be used for monitoring command to prevent running multiple monitpring process. The following settings will be used for monitoring

CONSISTENCY_PID_MONITORING_FILENAME (default: "consistency_monitoring")

CONSISTENCY_PID_MONITORING_FOLDER (default: None) - folder the pid file is stored. tempfile.gettempdir() is using if it is None

Contributing

We’re looking to grow the project and get more contributors especially to support more languages/versions. We’d also like to get the .pre-commit-hooks.yaml files added to popular linters without maintaining forks / mirrors.

Feel free to submit bug reports, pull requests, and feature requests.

Tools:

You might also like...
A set of high-level abstractions for Django forms

django-formtools Django's "formtools" is a set of high-level abstractions for Django forms. Currently for form previews and multi-step forms. This cod

I managed to attach the Django Framework to my Telegram Bot and set a webhook
I managed to attach the Django Framework to my Telegram Bot and set a webhook

I managed to attach the Django Framework to my Telegram Bot and set a webhook. I've been developing it from 10th of November 2021 and I want to have a basic working prototype.

Rosetta is a Django application that eases the translation process of your Django projects
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

A Django app to initialize Sentry client for your Django applications

Dj_sentry This Django application intialize Sentry SDK to your Django application. How to install You can install this packaging by using: pip install

Tools to easily create permissioned CRUD endpoints in graphene-django.

graphene-django-plus Tools to easily create permissioned CRUD endpoints in graphene-django. Install pip install graphene-django-plus To make use of ev

A Django web application that allows you to be in the loop about everything happening in your neighborhood.
A Django web application that allows you to be in the loop about everything happening in your neighborhood.

A Django web application that allows you to be in the loop about everything happening in your neighborhood. From contact information of different handyman to meeting announcements or even alerts.

Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django 🚀 Inspiration might be taken from @hotwired/hotwire-rails. We are sti

django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Comments
Owner
Occipital
Occipital
Keep track of failed login attempts in Django-powered sites.

django-axes Axes is a Django plugin for keeping track of suspicious login attempts for your Django based website and implementing simple brute-force a

Jazzband 1.1k Dec 30, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
An orgizational tool to keep track of tasks/projects and the time spent on them.

Django-Task-Manager Task Tracker using Python Django About The Project This project is an orgizational tool to keep track of tasks/projects and the ti

Nick Newton 1 Dec 21, 2021
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-dev 1.1k Dec 14, 2022
Helps working with singletons - things like global settings that you want to edit from the admin site.

Django Solo +---------------------------+ | | | | | \ | Django Solo helps

Sylvain Toé 726 Jan 8, 2023
Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app.

django-permissions-policy Set the draft security HTTP header Permissions-Policy (previously Feature-Policy) on your Django app. Requirements Python 3.

Adam Johnson 78 Jan 2, 2023
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022
A simple demonstration of how a django-based website can be set up for local development with microk8s

Django with MicroK8s Start Building Your Project This project provides a Django web app running as a single node Kubernetes cluster in microk8s. It is

Noah Jacobson 19 Oct 22, 2022