Explorar el Código

Closes #23725: Add parent-child relationships between jobs (#23761)

Allow jobs to reference a parent job to track related work.
Expose the relationship in the UI and REST API, including filtering and
child job status counts.

Preserve parent relationships when rescheduling recurring jobs and
retain child jobs when their parent is deleted.
Jeremy Stretch hace 2 horas
padre
commit
8a63074155

+ 6 - 0
docs/models/core/job.md

@@ -63,6 +63,12 @@ The job's access class, which determines which users may access the job in addit
 
 Any data associated with the execution of the job, such as log output.
 
+### Parent
+
+!!! info "This field was introduced in NetBox v4.8."
+
+The job which enqueued this job (if any). A parent does not wait for its children, and its status is independent of theirs. If the parent is deleted, its children are retained without a parent.
+
 ### Job ID
 
 The job's UUID, used for unique identification within a queue.

+ 22 - 0
docs/plugins/development/background-jobs.md

@@ -118,6 +118,28 @@ class MyModel(JobsMixin, NetBoxModel):
 ```
 
 
+### Child Jobs
+
+!!! info "This feature was introduced in NetBox v4.8."
+
+Pass `parent=self.job` to `enqueue()` or `enqueue_once()` when creating child jobs. Direct children appear on the generic job detail page and can be filtered by `parent_id` in the UI and REST API. Recurring jobs retain their parent; reusing an existing job leaves its parent unchanged.
+
+This records only where a job came from: a parent does not wait for its children, and its status is not affected by theirs. Deleting a parent leaves its children in place, without a parent.
+
+#### Example
+
+```python title="jobs.py"
+from netbox.jobs import JobRunner
+from .models import MyModel
+
+
+class NightlySweepJob(JobRunner):
+
+    def run(self, *args, **kwargs):
+        for obj in MyModel.objects.all():
+            MyTestJob.enqueue(instance=obj, parent=self.job)
+```
+
 ### Result URLs
 
 Use `core.utils.register_job_result_url()` to link jobs to your plugin's result page. Pass a model class or an `<app_label>.<model_name>` string, and optionally a `job_name`. The function receives a `Job` and returns a URL, or `None` to try the next fallback.

+ 18 - 3
netbox/core/api/serializers_/jobs.py

@@ -1,15 +1,27 @@
 from core.choices import *
 from core.models import Job
-from netbox.api.fields import ChoiceField, ContentTypeField
+from netbox.api.fields import ChoiceField, ContentTypeField, RelatedObjectCountField
 from netbox.api.gfk_fields import GFKSerializerField
 from netbox.api.serializers import BaseModelSerializer
 from users.api.serializers_.users import UserSerializer
 
 __all__ = (
     'JobSerializer',
+    'NestedJobSerializer',
 )
 
 
+class NestedJobSerializer(BaseModelSerializer):
+    """
+    Represents a Job related to another Job (e.g. its parent).
+    """
+    status = ChoiceField(choices=JobStatusChoices, read_only=True)
+
+    class Meta:
+        model = Job
+        fields = ['id', 'url', 'display_url', 'display', 'name', 'status', 'created', 'completed']
+
+
 class JobSerializer(BaseModelSerializer):
     user = UserSerializer(
         nested=True,
@@ -26,12 +38,15 @@ class JobSerializer(BaseModelSerializer):
     )
     notifications = ChoiceField(choices=JobNotificationChoices, read_only=True)
     access = ChoiceField(choices=JobAccessChoices, read_only=True)
+    parent = NestedJobSerializer(read_only=True, allow_null=True)
+    # Script results may be serialized without the viewset's count annotation.
+    child_count = RelatedObjectCountField('children', fallback_source='children.count')
 
     class Meta:
         model = Job
         fields = [
             'id', 'url', 'display_url', 'display', 'object_type', 'object_id', 'object', 'name', 'status', 'created',
             'scheduled', 'interval', 'started', 'completed', 'execution_time', 'user', 'data', 'error', 'job_id',
-            'queue_name', 'notifications', 'access', 'log_entries',
+            'queue_name', 'notifications', 'access', 'parent', 'child_count', 'log_entries',
         ]
-        brief_fields = ('url', 'created', 'completed', 'user', 'status')
+        brief_fields = ('id', 'url', 'display', 'name', 'created', 'completed', 'user', 'status')

+ 12 - 0
netbox/core/filtersets.py

@@ -172,6 +172,18 @@ class JobFilterSet(BaseFilterSet):
         to_field_name='username',
         label=_('User name'),
     )
+    parent_id = django_filters.ModelMultipleChoiceFilter(
+        field_name='parent',
+        queryset=Job.objects.all(),
+        distinct=False,
+        label=_('Parent job (ID)'),
+    )
+    has_parent = django_filters.BooleanFilter(
+        field_name='parent',
+        lookup_expr='isnull',
+        exclude=True,
+        label=_('Has a parent job'),
+    )
 
     class Meta:
         model = Job

+ 13 - 0
netbox/core/forms/filtersets.py

@@ -77,6 +77,7 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
     fieldsets = (
         FieldSet('q', 'filter_id'),
         FieldSet('object_type_id', 'status', 'access', 'queue_name', 'user_id', name=_('Attributes')),
+        FieldSet('parent_id', 'has_parent', name=_('Hierarchy')),
         FieldSet(
             'created__before', 'created__after', 'scheduled__before', 'scheduled__after', 'started__before',
             'started__after', 'completed__before', 'completed__after', name=_('Scheduling')
@@ -157,6 +158,18 @@ class JobFilterForm(SavedFiltersMixin, FilterForm):
         required=False,
         help_text=_('Seconds, or HH:MM:SS')
     )
+    parent_id = DynamicModelMultipleChoiceField(
+        queryset=Job.objects.all(),
+        required=False,
+        label=_('Parent job')
+    )
+    has_parent = forms.NullBooleanField(
+        required=False,
+        label=_('Has a parent job'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
 
 
 class ObjectChangeFilterForm(SavedFiltersMixin, FilterForm):

+ 25 - 0
netbox/core/migrations/0029_job_parent.py

@@ -0,0 +1,25 @@
+# Generated by Django 6.1.3 on 2026-11-20 19:14
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('core', '0028_populate_job_access'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='job',
+            name='parent',
+            field=models.ForeignKey(
+                blank=True,
+                null=True,
+                on_delete=django.db.models.deletion.SET_NULL,
+                related_name='children',
+                to='core.job',
+            ),
+        ),
+    ]

+ 23 - 0
netbox/core/models/jobs.py

@@ -125,6 +125,15 @@ class Job(models.Model):
         blank=True,
         help_text=_('Name of the queue in which this job was enqueued')
     )
+    parent = models.ForeignKey(
+        verbose_name=_('parent'),
+        to='self',
+        on_delete=models.SET_NULL,
+        related_name='children',
+        blank=True,
+        null=True,
+        help_text=_('The job which enqueued this job')
+    )
     notifications = models.CharField(
         verbose_name=_('notifications'),
         max_length=30,
@@ -189,6 +198,16 @@ class Job(models.Model):
                 _("Jobs cannot be assigned to this object type ({type}).").format(type=self.object_type)
             )
 
+    def save(self, *args, **kwargs):
+        # Parent is set only on creation: a worker's stale copy would otherwise overwrite SET_NULL on its deletion
+        if not self._state.adding and kwargs.get('update_fields') is None:
+            deferred = self.get_deferred_fields()
+            kwargs['update_fields'] = [
+                f.name for f in self._meta.concrete_fields
+                if not f.primary_key and f.name != 'parent' and f.attname not in deferred
+            ]
+        super().save(*args, **kwargs)
+
     @property
     def duration(self):
         if not self.completed:
@@ -328,6 +347,7 @@ class Job(models.Model):
             queue_name=None,
             notifications=None,
             access=None,
+            parent=None,
             **kwargs
     ):
         """
@@ -344,6 +364,7 @@ class Job(models.Model):
                 management commands only.
             notifications: Notification behavior on job completion (always, on_failure, or never)
             access: The job's access class (requester, object, or shared; defaults to shared)
+            parent: The Job which is enqueuing this job (optional)
         """
         if schedule_at and immediate:
             raise ValueError(_("enqueue() cannot be called with values for both schedule_at and immediate."))
@@ -372,6 +393,8 @@ class Job(models.Model):
             queue_name=rq_queue_name,
             notifications=notifications if notifications is not None else JobNotificationChoices.NOTIFICATION_ALWAYS,
             access=access,
+            # Assigned by ID, so the parent instance isn't pickled into the RQ payload
+            parent_id=parent.pk if parent else None,
         )
         job.full_clean()
         job.save()

+ 5 - 1
netbox/core/tables/jobs.py

@@ -54,6 +54,10 @@ class JobTable(NetBoxTable):
     access = columns.ChoiceFieldColumn(
         verbose_name=_('Access'),
     )
+    parent = tables.Column(
+        verbose_name=_('Parent'),
+        linkify=True
+    )
     log_entries = tables.Column(
         verbose_name=_('Log Entries'),
     )
@@ -65,7 +69,7 @@ class JobTable(NetBoxTable):
         model = Job
         fields = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'scheduled', 'interval', 'started',
-            'completed', 'execution_time', 'user', 'queue_name', 'access', 'log_entries', 'error', 'job_id',
+            'completed', 'execution_time', 'user', 'queue_name', 'access', 'log_entries', 'error', 'job_id', 'parent',
         )
         default_columns = (
             'pk', 'id', 'object_type', 'object', 'name', 'status', 'created', 'started', 'completed', 'execution_time',

+ 27 - 2
netbox/core/tests/test_api.py

@@ -12,7 +12,7 @@ from rq.job import Job as RQ_Job
 from rq.job import JobStatus
 from rq.registry import FailedJobRegistry, StartedJobRegistry
 
-from core.api.serializers import DataSourceSerializer
+from core.api.serializers import DataSourceSerializer, JobSerializer
 from dcim.choices import PortTypeChoices
 from dcim.models import FrontPort, PortMapping, RearPort, Site
 from users.constants import TOKEN_PREFIX
@@ -287,7 +287,7 @@ class JobTestCase(
     APIViewTestCases.ListObjectsViewTestCase,
 ):
     model = Job
-    brief_fields = ['completed', 'created', 'status', 'url', 'user']
+    brief_fields = ['completed', 'created', 'display', 'id', 'name', 'status', 'url', 'user']
 
     @classmethod
     def setUpTestData(cls):
@@ -370,6 +370,31 @@ class JobTestCase(
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertEqual(response.data['count'], 3)
 
+    def test_parent_and_child_count(self):
+        """Jobs expose their parent and a count of their children, and can be filtered by parent."""
+        self.add_permissions('core.view_job')
+        parent = Job.objects.get(name='Job 1')
+        Job.objects.filter(name__in=['Job 2', 'Job 3']).update(parent=parent)
+        url = reverse('core-api:job-list')
+
+        response = self.client.get(url, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        jobs = {job['name']: job for job in response.data['results']}
+        self.assertIsNone(jobs['Job 1']['parent'])
+        self.assertEqual(jobs['Job 1']['child_count'], 2)
+        self.assertEqual(jobs['Job 2']['parent']['id'], parent.pk)
+        self.assertEqual(jobs['Job 2']['parent']['name'], 'Job 1')
+        self.assertEqual(jobs['Job 2']['child_count'], 0)
+
+        response = self.client.get(f'{url}?parent_id={parent.pk}', **self.header)
+        self.assertEqual({job['name'] for job in response.data['results']}, {'Job 2', 'Job 3'})
+        response = self.client.get(f'{url}?has_parent=false', **self.header)
+        self.assertEqual({job['name'] for job in response.data['results']}, {'Job 1'})
+
+        # Serialized without the viewset's annotation (e.g. as a script's result), the count is queried
+        data = JobSerializer(parent, context={'request': response.wsgi_request}).data
+        self.assertEqual(data['child_count'], 2)
+
     def test_list_objects_reuse_object_serializer(self):
         """Jobs share one nested serializer per object type per request."""
         self.add_permissions('core.view_job')

+ 14 - 0
netbox/core/tests/test_filtersets.py

@@ -301,6 +301,20 @@ class JobTestCase(TestCase, BaseFilterSetTestMixin):
             ),
         )
         Job.objects.bulk_create(jobs)
+        Job.objects.filter(name__in=['Job 2', 'Job 3']).update(parent=jobs[0])
+
+    def test_parent(self):
+        """Filter Jobs by parent job (ID)."""
+        parent = Job.objects.get(name='Job 1')
+        params = {'parent_id': [parent.pk]}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
+    def test_has_parent(self):
+        """Filter Jobs by whether they have a parent job."""
+        params = {'has_parent': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'has_parent': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
     def test_user(self):
         """Filter Jobs by user (ID and username)."""

+ 89 - 0
netbox/core/tests/test_models.py

@@ -11,6 +11,7 @@ from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import ObjectDoesNotExist
 from django.core.management import call_command
 from django.db import IntegrityError, connection
+from django.db.models.signals import pre_save
 from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.urls import reverse
@@ -394,6 +395,94 @@ class JobTestCase(TestCase):
             **kwargs,
         )
 
+    def test_enqueue_with_parent(self):
+        """
+        A job enqueued with a parent records it, and the parent is not passed to the job's callable.
+        """
+        received = {}
+
+        def func(**kwargs):
+            received.update(kwargs)
+
+        parent = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        job = Job.enqueue(func, name='Child Job', immediate=True, parent=parent, foo='bar')
+
+        # The parent instance is not cached on the job, and so not pickled into its RQ payload
+        self.assertFalse(Job.parent.is_cached(job))
+        job.refresh_from_db()
+        self.assertEqual(job.parent, parent)
+        self.assertEqual(received['foo'], 'bar')
+        self.assertNotIn('parent', received)
+
+    @patch('core.models.jobs.django_rq.get_queue')
+    def test_delete_parent_retains_children(self, mock_get_queue):
+        """
+        Deleting a job leaves its children in place, without a parent.
+        """
+        parent = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        child = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER, parent=parent)
+
+        parent.delete()
+
+        child.refresh_from_db()
+        self.assertIsNone(child.parent)
+        # Only the parent's RQ job is canceled
+        mock_get_queue.return_value.fetch_job.assert_called_once_with(str(parent.job_id))
+
+    @patch('core.models.jobs.django_rq.get_queue')
+    def test_terminate_after_parent_deleted(self, mock_get_queue):
+        """
+        A copy of a job loaded before its parent was deleted does not restore the deleted parent when saved.
+        """
+        parent = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        child = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER, parent=parent)
+        stale_child = Job.objects.get(pk=child.pk)
+
+        parent.delete()
+        stale_child.terminate()
+
+        child.refresh_from_db()
+        self.assertIsNone(child.parent_id)
+        self.assertEqual(child.status, JobStatusChoices.STATUS_COMPLETED)
+
+    @patch('core.models.jobs.django_rq.get_queue')
+    def test_terminate_while_parent_deleted(self, mock_get_queue):
+        """
+        A job's parent being deleted during the save which terminates it does not fail the save.
+        """
+        parent = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        child = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER, parent=parent)
+
+        def delete_parent(sender, instance, **kwargs):
+            if instance.pk == child.pk:
+                Job.objects.filter(pk=parent.pk).delete()
+
+        pre_save.connect(delete_parent, sender=Job)
+        try:
+            child.terminate()
+        finally:
+            pre_save.disconnect(delete_parent, sender=Job)
+
+        # Foreign keys are checked at commit, which the test transaction never reaches
+        connection.check_constraints(table_names=[Job._meta.db_table])
+        child.refresh_from_db()
+        self.assertIsNone(child.parent_id)
+        self.assertEqual(child.status, JobStatusChoices.STATUS_COMPLETED)
+
+    def test_save_does_not_query_parent(self):
+        """
+        Saving an existing job issues only its update, which leaves the parent unwritten.
+        """
+        parent = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER)
+        child = self._make_job(None, JobNotificationChoices.NOTIFICATION_NEVER, parent=parent)
+
+        with CaptureQueriesContext(connection) as ctx:
+            child.save()
+            child.save(update_fields=['status'])
+        job_queries = [q['sql'] for q in ctx.captured_queries if '"core_job"' in q['sql']]
+        self.assertEqual(len(job_queries), 2)
+        self.assertTrue(all(sql.startswith('UPDATE') and '"parent_id"' not in sql for sql in job_queries))
+
     @patch('core.models.jobs.django_rq.get_queue')
     def test_delete_cancels_job_from_correct_queue(self, mock_get_queue):
         """

+ 44 - 0
netbox/core/tests/test_views.py

@@ -206,6 +206,50 @@ class JobTestCase(
                 ),
             ]
         )
+        Job.objects.filter(name__in=['Job 1', 'Job 3']).update(parent=Job.objects.get(name='Job 2'))
+
+    def test_parent_lists_children(self):
+        """A job's page lists its children, with a count per status."""
+        self.add_permissions('core.view_job')
+        parent = Job.objects.get(name='Job 2')
+
+        response = self.client.get(reverse('core:job', args=[parent.pk]))
+        self.assertHttpStatus(response, 200)
+        content = response.content.decode()
+        self.assertIn('Child jobs', content)
+        self.assertIn('1 Pending', content)
+        self.assertIn('1 Completed', content)
+        self.assertNotIn('Errored', content)
+        self.assertIn(f'parent_id={parent.pk}&amp;status=completed', content)
+
+    def test_child_links_to_parent(self):
+        """A child job's page links to its parent, and lists no children."""
+        self.add_permissions('core.view_job')
+        parent = Job.objects.get(name='Job 2')
+        child = Job.objects.get(name='Job 1')
+
+        response = self.client.get(reverse('core:job', args=[child.pk]))
+        self.assertHttpStatus(response, 200)
+        content = response.content.decode()
+        self.assertIn(reverse('core:job', args=[parent.pk]), content)
+        self.assertNotIn('Child jobs', content)
+
+    def test_child_counts_respect_permissions(self):
+        """Child counts include only the jobs the user may view."""
+        obj_perm = ObjectPermission(
+            name='View some jobs',
+            constraints={'status__in': [JobStatusChoices.STATUS_RUNNING, JobStatusChoices.STATUS_COMPLETED]},
+            actions=['view'],
+        )
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(Job))
+
+        response = self.client.get(reverse('core:job', args=[Job.objects.get(name='Job 2').pk]))
+        self.assertHttpStatus(response, 200)
+        content = response.content.decode()
+        self.assertIn('1 Completed', content)
+        self.assertNotIn('1 Pending', content)
 
 
 class ObjectJobsViewTestCase(TestCase):

+ 42 - 0
netbox/core/ui/panels.py

@@ -1,5 +1,9 @@
+from django.db.models import Count
+from django.urls import reverse
+from django.utils.http import urlencode
 from django.utils.translation import gettext_lazy as _
 
+from core.choices import JobStatusChoices
 from netbox.ui import attrs, panels
 
 
@@ -55,6 +59,44 @@ class JobPanel(panels.ObjectAttributesPanel):
     error = attrs.TextAttr('error')
     user = attrs.TextAttr('user', label=_('Created by'))
     access = attrs.ChoiceAttr('access')
+    parent = attrs.RelatedObjectAttr('parent', linkify=True, label=_('Parent job'))
+
+
+class ChildJobsPanel(panels.ObjectsTablePanel):
+    """
+    Lists a job's direct children, with a count of them per status. Hidden if there are none.
+    """
+    template_name = 'core/panels/child_jobs.html'
+    title = _('Child jobs')
+
+    def __init__(self, **kwargs):
+        super().__init__(
+            model='core.job',
+            filters={'parent_id': lambda ctx: ctx['object'].pk},
+            exclude_columns=['parent'],
+            **kwargs,
+        )
+
+    def get_context(self, context):
+        ctx = super().get_context(context)
+        job = ctx['object']
+        children = job.children.all()
+        if request := ctx['request']:
+            children = children.restrict(request.user, 'view')
+        counts = dict(children.order_by().values_list('status').annotate(count=Count('pk')))
+        list_url = reverse('core:job_list')
+        ctx['status_counts'] = [
+            {
+                'text': f'{counts[status]} {label}',
+                'color': JobStatusChoices.colors.get(status),
+                'url': f'{list_url}?{urlencode({"parent_id": job.pk, "status": status})}',
+            }
+            for status, label in JobStatusChoices if status in counts
+        ]
+        return ctx
+
+    def should_render(self, context):
+        return bool(context['status_counts']) and super().should_render(context)
 
 
 class JobSchedulingPanel(panels.ObjectAttributesPanel):

+ 1 - 0
netbox/core/views.py

@@ -259,6 +259,7 @@ class JobView(generic.ObjectView):
             panels.JobSchedulingPanel(),
         ],
         bottom_panels=[
+            panels.ChildJobsPanel(),
             JSONPanel('data', title=_('Data')),
         ],
     )

+ 18 - 0
netbox/extras/tests/test_views.py

@@ -1790,6 +1790,24 @@ class ScriptResultViewTestCase(TestCase):
         self.assertHttpStatus(response, 404)
         self.assertNotIn(self.SECRET_OUTPUT.encode(), response.content)
 
+    def test_links_to_related_jobs(self):
+        """
+        A script result links to the generic job page when the job has a parent or children.
+        """
+        self.add_permissions('extras.view_script', 'core.view_job')
+        url = reverse('extras:script_result', kwargs={'job_pk': self.allowed_job.pk})
+        job_url = reverse('core:job', args=[self.allowed_job.pk])
+
+        self.assertNotIn(f'href="{job_url}"', self.client.get(url).content.decode())
+
+        parent = Job.objects.create(name='parent-job', job_id=uuid.uuid4())
+        Job.objects.filter(pk=self.allowed_job.pk).update(parent=parent)
+        self.assertIn(f'href="{job_url}"', self.client.get(url).content.decode())
+
+        Job.objects.filter(pk=self.allowed_job.pk).update(parent=None)
+        Job.objects.filter(pk=self.secret_job.pk).update(parent=self.allowed_job)
+        self.assertIn(f'href="{job_url}"', self.client.get(url).content.decode())
+
 
 class ScriptJobsRestrictionTestCase(TestCase):
     """

+ 3 - 0
netbox/extras/views.py

@@ -1942,6 +1942,9 @@ class ScriptResultView(TableMixin, generic.ObjectView):
                 response.status_code = 286
             return response
 
+        # This page bypasses the generic job layout, so link to it for the job's parent and children
+        context['has_related_jobs'] = bool(job.parent_id) or job.children.restrict(request.user, 'view').exists()
+
         return render(request, 'extras/script_result.html', context)
 
 

+ 1 - 0
netbox/netbox/jobs.py

@@ -199,6 +199,7 @@ class JobRunner(ABC):
                 interval=job.interval,
                 notifications=job.notifications,
                 access=job.access,
+                parent=Job.objects.filter(pk=job.parent_id).first() if job.parent_id else None,
                 **kwargs,
             )
         except (ValidationError, ValueError) as e:

+ 54 - 0
netbox/netbox/tests/test_jobs.py

@@ -278,6 +278,28 @@ class JobRunnerTestCase(BaseJobRunnerTestCase):
                 self.assertEqual(observed, [(status, [successor.pk])])
                 self.assertEqual((successor.status, successor.interval), (JobStatusChoices.STATUS_SCHEDULED, 60))
 
+    def test_handle_reschedules_with_parent(self):
+        """A recurring job's successor keeps its parent, unless the parent has been deleted."""
+        parent = Job.objects.create(name='Parent', job_id=uuid.uuid4())
+        for delete_parent in (False, True):
+            with self.subTest(delete_parent=delete_parent):
+                # Assigned by ID, as in an enqueued job's RQ payload
+                job = Job.objects.create(
+                    name=TestJobRunner.name, interval=60, job_id=uuid.uuid4(), parent_id=parent.pk
+                )
+                if delete_parent:
+                    with patch('core.models.jobs.django_rq.get_queue'):
+                        parent.delete()
+
+                with patch.object(TestJobRunner, 'run'):
+                    TestJobRunner.handle(job)
+
+                successor = Job.objects.filter(
+                    name=TestJobRunner.name, status=JobStatusChoices.STATUS_SCHEDULED
+                ).exclude(pk=job.pk).latest('created')
+                self.assertEqual(successor.parent_id, None if delete_parent else parent.pk)
+                successor.delete()
+
     def test_handle_reschedule_keeps_access(self):
         """A periodic job's successor has the same access class."""
         instance = DataSource.objects.create(name='Data Source 1', type='local')
@@ -656,6 +678,38 @@ class EnqueueTestCase(BaseJobRunnerTestCase):
         self.assertRaises(Job.DoesNotExist, job1.refresh_from_db)
         self.assertEqual(TestJobRunner.get_jobs(instance).count(), 1)
 
+    def test_enqueue_with_parent(self):
+        parent = TestJobRunner.enqueue(schedule_at=self.get_schedule_at())
+        child = TestJobRunner.enqueue(schedule_at=self.get_schedule_at(), parent=parent)
+        once = TestJobRunner.enqueue_once(instance=DataSource(), schedule_at=self.get_schedule_at(), parent=parent)
+
+        self.assertIsNone(parent.parent)
+        self.assertEqual(child.parent, parent)
+        self.assertEqual(once.parent, parent)
+        self.assertEqual(set(parent.children.all()), {child, once})
+
+    def test_enqueue_once_reuse_keeps_parent(self):
+        """Reusing an existing job leaves its original parent (or lack of one) unchanged."""
+        instance = DataSource.objects.create(name='Source 1', type='local')
+        schedule_at = self.get_schedule_at()
+        parent1 = TestJobRunner.enqueue(schedule_at=self.get_schedule_at())
+        parent2 = TestJobRunner.enqueue(schedule_at=self.get_schedule_at())
+
+        job1 = TestJobRunner.enqueue_once(instance, schedule_at=schedule_at, parent=parent1)
+        for parent in (parent2, None):
+            with self.subTest(parent=parent):
+                job2 = TestJobRunner.enqueue_once(instance, schedule_at=schedule_at, parent=parent)
+                self.assertEqual(job1, job2)
+                job1.refresh_from_db()
+                self.assertEqual(job1.parent, parent1)
+
+        # Likewise for a job enqueued without a parent
+        instance = DataSource.objects.create(name='Source 2', type='local')
+        job1 = TestJobRunner.enqueue_once(instance, schedule_at=schedule_at)
+        TestJobRunner.enqueue_once(instance, schedule_at=schedule_at, parent=parent1)
+        job1.refresh_from_db()
+        self.assertIsNone(job1.parent)
+
 
 class SystemJobTestCase(BaseJobRunnerTestCase):
     """

+ 10 - 0
netbox/templates/core/panels/child_jobs.html

@@ -0,0 +1,10 @@
+{% extends 'ui/panels/objects_table.html' %}
+
+{% block panel_content %}
+  <div class="card-body">
+    {% for status in status_counts %}
+      {% badge status.text bg_color=status.color url=status.url %}
+    {% endfor %}
+  </div>
+  {{ block.super }}
+{% endblock panel_content %}

+ 6 - 1
netbox/templates/extras/script_result.html

@@ -61,7 +61,12 @@
           </div>
         </div>
 
-        <div class="ms-auto d-print-none">
+        <div class="ms-auto d-print-none d-flex gap-2">
+          {% if has_related_jobs %}
+            <a href="{% url 'core:job' pk=job.pk %}" class="btn btn-outline-secondary">
+              <i class="mdi mdi-file-tree"></i> {% trans "Related Jobs" %}
+            </a>
+          {% endif %}
           {% if request.user.is_authenticated and job.completed %}
             <div class="table-configure input-group">
               <button type="button" data-bs-toggle="modal" title="{% trans "Configure Table" %}" data-bs-target="#ObjectTable_config"