Reputation: 7260
I've got this custom admin command to remove some old records. QuerySets are lazy so I was wondering if there is a way to optimize this code because at the moment there are four hits to database in --dry-run
mode:
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--dry-run', action='store_true')
def handle(self, *args, **options):
threshold = timezone.now() - timezone.timedelta(5)
try:
if options['dry_run']:
queryset = Mointor.objects.filter(created__lt=threshold)
if queryset.exists():
msg = f'{queryset.count()} record(s) will be deleted, from {queryset.first().created} to {queryset.last().created}'
else:
msg = 'No records to delete'
else:
Monitor.objects.filter(created__lt=threshold).delete()
msg = 'OK'
except Exception as e:
raise CommandError(e)
self.stdout.write(msg)
Upvotes: 1
Views: 45
Reputation: 4034
You can firsty do count = queryset.count()
and then use it as if
condition and insert inside string. So you will get rid of exists
query. Also to find date range, you can use aggregate
with Min
and Max
, so you have saved another query here. But as for me, it is not really a problem. Remember, don't optimize prematurely unless you are sure you have a performance issue.
Upvotes: 2