Skip to content

Instantly share code, notes, and snippets.

@StevenMapes
Last active July 2, 2025 16:11
Show Gist options
  • Save StevenMapes/aacee8c2787c2ade4864ee06457276f2 to your computer and use it in GitHub Desktop.
Save StevenMapes/aacee8c2787c2ade4864ee06457276f2 to your computer and use it in GitHub Desktop.
Django Management command to clear down django-silk entries that are older than N hours ago.
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection
from django.utils.timezone import now
class Command(BaseCommand):
"""Clears down the silk records directly against the database basd upon time"""
def handle(self, *args, **options):
"""Default to 24 hours ago but allows overloading via Django settings variable"""
hours = 24
if hasattr(settings, "SILK_DELETE_OLDER_THAN_HOURS"):
hours = settings.SILK_DELETE_OLDER_THAN_HOURS
time_ago = now() - relativedelta(hours=hours)
sqls = [
"DELETE q FROM silk_profile_queries AS q JOIN silk_profile AS p ON p.id = q.profile_id JOIN silk_request AS r ON r.id = p.request_id WHERE r.start_time < %s",
"DELETE q FROM silk_profile AS q JOIN silk_profile AS r ON r.id = q.request_id WHERE r.start_time < %s",
"DELETE q FROM silk_sqlquery AS q JOIN silk_request AS r ON r.id = q.request_id WHERE r.start_time < %s",
"DELETE q FROM silk_response AS q JOIN silk_request AS r ON r.id = q.request_id WHERE r.start_time < %s",
"DELETE r FROM silk_request AS r WHERE r.start_time < %s"
]
with connection.cursor() as cursor:
for sql in sqls:
cursor.execute(sql, [time_ago])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment