Skip to content

Commit 20dab41

Browse files
authored
Add a task_name property to DBTaskResult (#127)
If a task still exists - use that for the name. However if the underlying function no longer exists - use task_path to come up with an appropriate name to show in the admin.
1 parent dd1eb52 commit 20dab41

File tree

3 files changed

+31
-5
lines changed

3 files changed

+31
-5
lines changed

django_tasks/backends/database/admin.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class DBTaskResultAdmin(admin.ModelAdmin):
1111
list_display = (
1212
"id",
13-
"get_task_name",
13+
"task_name",
1414
"status",
1515
"enqueued_at",
1616
"started_at",
@@ -40,7 +40,3 @@ def get_readonly_fields(
4040
self, request: HttpRequest, obj: Optional[DBTaskResult] = None
4141
) -> List[str]:
4242
return [f.name for f in self.model._meta.fields]
43-
44-
@admin.display(description="Task")
45-
def get_task_name(self, obj: DBTaskResult) -> str:
46-
return obj.task.name

django_tasks/backends/database/models.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,20 @@ def task_result(self) -> "TaskResult[T]":
170170

171171
return task_result
172172

173+
@property
174+
def task_name(self) -> str:
175+
# If the function for an existing task is no longer available, it'll either raise an
176+
# ImportError or ModuleNotFoundError (a subclass of ImportError).
177+
try:
178+
return self.task.name
179+
except ImportError:
180+
pass
181+
182+
try:
183+
return self.task_path.rsplit(".", 1)[1]
184+
except IndexError:
185+
return self.task_path
186+
173187
@retry(backoff_delay=0)
174188
def claim(self) -> None:
175189
"""

tests/tests/test_database_backend.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,22 @@ def test_missing_task_path(self) -> None:
232232
with self.assertRaises(ImportError):
233233
_ = db_task_result.task
234234

235+
def test_task_name(self) -> None:
236+
for task_path, expected_task_name in [
237+
("tests.tasks.noop_task", "noop_task"),
238+
("tests.tasks.task_not_found", "task_not_found"),
239+
("tests.tasks.module_not_found.module_not_found", "module_not_found"),
240+
("unexpected_function", "unexpected_function"),
241+
]:
242+
with self.subTest(task_path):
243+
db_task_result = DBTaskResult.objects.create(
244+
args_kwargs={"args": [], "kwargs": {}},
245+
task_path=task_path,
246+
backend_name="default",
247+
)
248+
249+
self.assertEqual(db_task_result.task_name, expected_task_name)
250+
235251
def test_check(self) -> None:
236252
errors = list(default_task_backend.check())
237253

0 commit comments

Comments
 (0)