CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-prometheus

Django middlewares to monitor your application with Prometheus.io

Pending
Overview
Eval results
Files

model-monitoring.mddocs/

Model Monitoring

Monitor Django model operations (insert, update, delete) by model name through mixin classes that instrument Django ORM operations. This provides visibility into data modification patterns and database usage.

Capabilities

Model Operations Mixin

Factory function that creates mixin classes to track model lifecycle operations with Prometheus metrics.

def ExportModelOperationsMixin(model_name: str):
    """
    Returns a mixin class for models to export counters for lifecycle operations.
    
    Usage:
      class User(ExportModelOperationsMixin('user'), Model):
          ...
    
    Parameters:
    - model_name: str, name of the model for metric labeling
    
    Returns:
    Mixin class with instrumented _do_insert, _do_update, delete methods
    """

The returned mixin class instruments the following Django model methods:

class ExportModelOperationsMixin:
    """
    Mixin class that instruments Django model operations for monitoring.
    This class is dynamically created by ExportModelOperationsMixin function.
    """
    
    def _do_insert(self, *args, **kwargs):
        """
        Instrumented version of Django's _do_insert method.
        Increments model_inserts counter before calling parent method.
        
        Parameters:
        - *args: Arguments passed to parent _do_insert
        - **kwargs: Keyword arguments passed to parent _do_insert
        
        Returns:
        Result from parent _do_insert method
        """
    
    def _do_update(self, *args, **kwargs):
        """
        Instrumented version of Django's _do_update method.
        Increments model_updates counter before calling parent method.
        
        Parameters:
        - *args: Arguments passed to parent _do_update
        - **kwargs: Keyword arguments passed to parent _do_update
        
        Returns:
        Result from parent _do_update method
        """
    
    def delete(self, *args, **kwargs):
        """
        Instrumented version of Django's delete method.
        Increments model_deletes counter before calling parent method.
        
        Parameters:
        - *args: Arguments passed to parent delete
        - **kwargs: Keyword arguments passed to parent delete
        
        Returns:
        Result from parent delete method
        """

Monitored Metrics

Model Operation Counters

  • django_model_inserts_total: Number of insert operations by model (labeled by model name)
  • django_model_updates_total: Number of update operations by model (labeled by model name)
  • django_model_deletes_total: Number of delete operations by model (labeled by model name)

Usage Examples

Basic Model Monitoring

from django.db import models
from django_prometheus.models import ExportModelOperationsMixin

class User(ExportModelOperationsMixin('user'), models.Model):
    username = models.CharField(max_length=100)
    email = models.EmailField()
    created_at = models.DateTimeField(auto_now_add=True)

class Product(ExportModelOperationsMixin('product'), models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.CharField(max_length=100)

class Order(ExportModelOperationsMixin('order'), models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=50)

Using the Monitored Models

# These operations will be automatically tracked in Prometheus metrics

# Create operations (tracked as inserts)
user = User.objects.create(username='john_doe', email='john@example.com')
product = Product.objects.create(name='Widget', price=19.99, category='tools')

# Update operations (tracked as updates)
user.email = 'john.doe@example.com'
user.save()

# Delete operations (tracked as deletes)
old_products = Product.objects.filter(price__lt=10.00)
for product in old_products:
    product.delete()

# Bulk operations
User.objects.filter(username__startswith='test_').delete()  # Multiple deletes tracked

Custom Model Names

# Use descriptive model names for better metric organization
class BlogPost(ExportModelOperationsMixin('blog_post'), models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()

class UserProfile(ExportModelOperationsMixin('user_profile'), models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()

# Model names will appear in metrics as:
# django_model_inserts_total{model="blog_post"}
# django_model_updates_total{model="user_profile"}
# etc.

Monitoring Specific Model Subsets

# Monitor only critical models that need tracking
class CriticalData(ExportModelOperationsMixin('critical_data'), models.Model):
    sensitive_field = models.CharField(max_length=100)
    
class RegularData(models.Model):  # Not monitored
    normal_field = models.CharField(max_length=100)

Metric Labels

All model operation metrics include the following label:

  • model: The model name specified in the ExportModelOperationsMixin call

Notes

  • The mixin must be listed before models.Model in the inheritance chain
  • Model names in metrics use the string passed to ExportModelOperationsMixin(), not the actual class name
  • Bulk operations (like QuerySet.delete()) will track each individual delete operation
  • The mixin only tracks operations that go through Django's ORM methods
  • Raw SQL operations are not tracked by this mixin (use database monitoring for those)

Install with Tessl CLI

npx tessl i tessl/pypi-django-prometheus

docs

cache-monitoring.md

database-monitoring.md

http-monitoring.md

index.md

metrics-export.md

migration-monitoring.md

model-monitoring.md

testing-utilities.md

tile.json