0
# Model Monitoring
1
2
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.
3
4
## Capabilities
5
6
### Model Operations Mixin
7
8
Factory function that creates mixin classes to track model lifecycle operations with Prometheus metrics.
9
10
```python { .api }
11
def ExportModelOperationsMixin(model_name: str):
12
"""
13
Returns a mixin class for models to export counters for lifecycle operations.
14
15
Usage:
16
class User(ExportModelOperationsMixin('user'), Model):
17
...
18
19
Parameters:
20
- model_name: str, name of the model for metric labeling
21
22
Returns:
23
Mixin class with instrumented _do_insert, _do_update, delete methods
24
"""
25
```
26
27
The returned mixin class instruments the following Django model methods:
28
29
```python { .api }
30
class ExportModelOperationsMixin:
31
"""
32
Mixin class that instruments Django model operations for monitoring.
33
This class is dynamically created by ExportModelOperationsMixin function.
34
"""
35
36
def _do_insert(self, *args, **kwargs):
37
"""
38
Instrumented version of Django's _do_insert method.
39
Increments model_inserts counter before calling parent method.
40
41
Parameters:
42
- *args: Arguments passed to parent _do_insert
43
- **kwargs: Keyword arguments passed to parent _do_insert
44
45
Returns:
46
Result from parent _do_insert method
47
"""
48
49
def _do_update(self, *args, **kwargs):
50
"""
51
Instrumented version of Django's _do_update method.
52
Increments model_updates counter before calling parent method.
53
54
Parameters:
55
- *args: Arguments passed to parent _do_update
56
- **kwargs: Keyword arguments passed to parent _do_update
57
58
Returns:
59
Result from parent _do_update method
60
"""
61
62
def delete(self, *args, **kwargs):
63
"""
64
Instrumented version of Django's delete method.
65
Increments model_deletes counter before calling parent method.
66
67
Parameters:
68
- *args: Arguments passed to parent delete
69
- **kwargs: Keyword arguments passed to parent delete
70
71
Returns:
72
Result from parent delete method
73
"""
74
```
75
76
## Monitored Metrics
77
78
### Model Operation Counters
79
- `django_model_inserts_total`: Number of insert operations by model (labeled by model name)
80
- `django_model_updates_total`: Number of update operations by model (labeled by model name)
81
- `django_model_deletes_total`: Number of delete operations by model (labeled by model name)
82
83
## Usage Examples
84
85
### Basic Model Monitoring
86
87
```python
88
from django.db import models
89
from django_prometheus.models import ExportModelOperationsMixin
90
91
class User(ExportModelOperationsMixin('user'), models.Model):
92
username = models.CharField(max_length=100)
93
email = models.EmailField()
94
created_at = models.DateTimeField(auto_now_add=True)
95
96
class Product(ExportModelOperationsMixin('product'), models.Model):
97
name = models.CharField(max_length=200)
98
price = models.DecimalField(max_digits=10, decimal_places=2)
99
category = models.CharField(max_length=100)
100
101
class Order(ExportModelOperationsMixin('order'), models.Model):
102
user = models.ForeignKey(User, on_delete=models.CASCADE)
103
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
104
status = models.CharField(max_length=50)
105
```
106
107
### Using the Monitored Models
108
109
```python
110
# These operations will be automatically tracked in Prometheus metrics
111
112
# Create operations (tracked as inserts)
113
user = User.objects.create(username='john_doe', email='john@example.com')
114
product = Product.objects.create(name='Widget', price=19.99, category='tools')
115
116
# Update operations (tracked as updates)
117
user.email = 'john.doe@example.com'
118
user.save()
119
120
# Delete operations (tracked as deletes)
121
old_products = Product.objects.filter(price__lt=10.00)
122
for product in old_products:
123
product.delete()
124
125
# Bulk operations
126
User.objects.filter(username__startswith='test_').delete() # Multiple deletes tracked
127
```
128
129
### Custom Model Names
130
131
```python
132
# Use descriptive model names for better metric organization
133
class BlogPost(ExportModelOperationsMixin('blog_post'), models.Model):
134
title = models.CharField(max_length=200)
135
content = models.TextField()
136
137
class UserProfile(ExportModelOperationsMixin('user_profile'), models.Model):
138
user = models.OneToOneField(User, on_delete=models.CASCADE)
139
bio = models.TextField()
140
141
# Model names will appear in metrics as:
142
# django_model_inserts_total{model="blog_post"}
143
# django_model_updates_total{model="user_profile"}
144
# etc.
145
```
146
147
### Monitoring Specific Model Subsets
148
149
```python
150
# Monitor only critical models that need tracking
151
class CriticalData(ExportModelOperationsMixin('critical_data'), models.Model):
152
sensitive_field = models.CharField(max_length=100)
153
154
class RegularData(models.Model): # Not monitored
155
normal_field = models.CharField(max_length=100)
156
```
157
158
## Metric Labels
159
160
All model operation metrics include the following label:
161
- `model`: The model name specified in the ExportModelOperationsMixin call
162
163
## Notes
164
165
- The mixin must be listed before `models.Model` in the inheritance chain
166
- Model names in metrics use the string passed to `ExportModelOperationsMixin()`, not the actual class name
167
- Bulk operations (like `QuerySet.delete()`) will track each individual delete operation
168
- The mixin only tracks operations that go through Django's ORM methods
169
- Raw SQL operations are not tracked by this mixin (use database monitoring for those)