Celery Result Backends using the Django ORM/Cache framework
npx @tessl/cli install tessl/pypi-django-celery-results@2.6.00
# Django Celery Results
1
2
A Django extension providing database and cache backends for storing Celery task results. It enables developers to store and retrieve Celery task results using Django's ORM models and caching framework, allowing task results to be queried like any other Django model.
3
4
## Package Information
5
6
- **Package Name**: django-celery-results
7
- **Language**: Python
8
- **Installation**: `pip install django-celery-results`
9
10
## Core Imports
11
12
```python
13
import django_celery_results
14
```
15
16
Backend imports for configuration:
17
18
```python
19
from django_celery_results.backends import DatabaseBackend, CacheBackend
20
```
21
22
Model imports for querying results:
23
24
```python
25
from django_celery_results.models import TaskResult, GroupResult, ChordCounter
26
```
27
28
App configuration import:
29
30
```python
31
from django_celery_results.apps import CeleryResultConfig
32
```
33
34
Utility function imports:
35
36
```python
37
from django_celery_results.utils import now
38
```
39
40
## Basic Usage
41
42
### Installation and Configuration
43
44
```python
45
# settings.py
46
INSTALLED_APPS = [
47
# ... other apps
48
'django_celery_results',
49
]
50
51
# Configure Celery to use Django database backend
52
CELERY_RESULT_BACKEND = 'django-db'
53
54
# Or use Django cache backend
55
# CELERY_RESULT_BACKEND = 'django-cache'
56
57
# Optional: Configure task ID max length (useful for MySQL)
58
DJANGO_CELERY_RESULTS_TASK_ID_MAX_LENGTH = 191
59
```
60
61
### Querying Task Results
62
63
```python
64
from django_celery_results.models import TaskResult
65
from celery.result import AsyncResult
66
67
# Query task results using Django ORM
68
recent_tasks = TaskResult.objects.filter(
69
status='SUCCESS',
70
date_done__gte=timezone.now() - timedelta(hours=1)
71
)
72
73
for task in recent_tasks:
74
print(f"Task {task.task_id}: {task.status}")
75
print(f"Result: {task.result}")
76
77
# Use Celery's AsyncResult with the backend
78
result = AsyncResult('task-id-here')
79
print(f"Task state: {result.state}")
80
print(f"Task result: {result.result}")
81
```
82
83
## Architecture
84
85
Django Celery Results provides two main backend implementations:
86
87
- **DatabaseBackend**: Stores task results in Django database tables using the ORM
88
- **CacheBackend**: Stores task results in Django's cache framework
89
- **Models**: Django models (TaskResult, GroupResult, ChordCounter) for database storage
90
- **Managers**: Custom managers providing database operations with transaction retry logic
91
- **Admin Integration**: Django admin interfaces for browsing and managing task results
92
- **REST Views**: HTTP endpoints for checking task and group status via JSON APIs
93
94
The package integrates seamlessly with Celery's result backend system while providing the full power of Django's ORM for querying and managing task results.
95
96
## Capabilities
97
98
### Result Backend Configuration
99
100
Configuration of Celery result backends using Django's database or cache frameworks. Provides both database-based and cache-based storage with automatic encoding/decoding of task results.
101
102
```python { .api }
103
class DatabaseBackend(BaseDictBackend):
104
def __init__(self, *args, **kwargs): ...
105
def exception_safe_to_retry(self, exc): ...
106
def encode_content(self, data): ...
107
def decode_content(self, obj, content): ...
108
def cleanup(self): ...
109
110
class CacheBackend(KeyValueStoreBackend):
111
def __init__(self, *args, **kwargs): ...
112
def get(self, key): ...
113
def set(self, key, value): ...
114
def delete(self, key): ...
115
```
116
117
[Backend Configuration](./backends.md)
118
119
### Task Result Models
120
121
Django models for storing and querying Celery task results, group results, and chord coordination data. Provides full ORM capabilities for result management and includes custom managers with retry logic.
122
123
```python { .api }
124
class TaskResult(models.Model):
125
task_id: models.CharField
126
task_name: models.CharField
127
status: models.CharField
128
result: models.TextField
129
date_created: models.DateTimeField
130
date_done: models.DateTimeField
131
132
def as_dict(self): ...
133
134
class GroupResult(models.Model):
135
group_id: models.CharField
136
result: models.TextField
137
date_created: models.DateTimeField
138
date_done: models.DateTimeField
139
140
def as_dict(self): ...
141
142
class ChordCounter(models.Model):
143
group_id: models.CharField
144
sub_tasks: models.TextField
145
count: models.PositiveIntegerField
146
147
def group_result(self, app=None): ...
148
```
149
150
[Task Result Models](./models.md)
151
152
### Admin Interface
153
154
Django admin integration for browsing, searching, and managing task results through the web interface. Provides read-only or editable views based on configuration.
155
156
```python { .api }
157
class TaskResultAdmin(admin.ModelAdmin):
158
model: TaskResult
159
list_display: tuple
160
list_filter: tuple
161
search_fields: tuple
162
163
def get_readonly_fields(self, request, obj=None): ...
164
165
class GroupResultAdmin(admin.ModelAdmin):
166
model: GroupResult
167
list_display: tuple
168
search_fields: tuple
169
```
170
171
[Admin Interface](./admin.md)
172
173
### REST API Views
174
175
HTTP endpoints for checking task and group execution status, returning JSON responses suitable for web applications and AJAX requests.
176
177
```python { .api }
178
def task_status(request, task_id):
179
"""Get detailed task status and result in JSON format."""
180
181
def is_task_successful(request, task_id):
182
"""Check if a task completed successfully."""
183
184
def group_status(request, group_id):
185
"""Get detailed status for all tasks in a group."""
186
187
def is_group_successful(request, group_id):
188
"""Check if all tasks in a group completed successfully."""
189
```
190
191
[REST API Views](./views.md)
192
193
### Django App Configuration
194
195
Django application configuration class providing package metadata and settings for the django-celery-results app.
196
197
```python { .api }
198
class CeleryResultConfig(AppConfig):
199
"""Default configuration for the django_celery_results app."""
200
201
name: str # 'django_celery_results'
202
label: str # 'django_celery_results'
203
verbose_name: str # 'Celery Results'
204
default_auto_field: str # 'django.db.models.AutoField'
205
```
206
207
### Utility Functions
208
209
Helper functions for time handling that work correctly with Django timezone settings.
210
211
```python { .api }
212
def now():
213
"""
214
Return the current date and time with proper timezone handling.
215
216
Returns:
217
datetime: Current timestamp respecting Django USE_TZ setting
218
"""
219
```