Skip to content

Commit

Permalink
Add management command to recover deleted attachments
Browse files Browse the repository at this point in the history
  • Loading branch information
DavisRayM committed Apr 20, 2020
1 parent 75e04c7 commit 8299fbb
Showing 1 changed file with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from django.core.management.base import BaseCommand

from onadata.apps.logger.models import Instance


def recover_soft_deleted_attachments(self, form_id, stdout=None):
"""
Recovers attachments that were accidentally soft-deleted
:param: (str) form_id: Unique identifier for a XForm object
:param: (sys.stdout) stdout: Python standard output. Default: None
"""
instances = Instance.objects.filter(
xform__id=form_id, deleted_at__isnull=True)
for instance in instances:
expected_no_of_attachments = instance.get_expected_media()
if not instance.attachments.filter(
deleted_at__isnull=True) == expected_no_of_attachments:
attachments_to_recover = instance.attachments.filter(
deleted_at__isnull=False,
name__in=instance.get_expected_media())
for attachment in attachments_to_recover:
attachment.deleted_at = None
attachment.deleted_by = None
attachment.save()

if stdout:
stdout.write(
f'Recovered {attachment.name} ID: {attachment.id}')


class Command(BaseCommand):
help = 'Restore wrongly deleted attachments'

def add_arguments(self, parser):
parser.add_argument('-f', '--form', dest='form_id', type=int)

def handle(self, *args, **options):
form_id = options.get('form_id')
recover_soft_deleted_attachments(self, form_id, self.stdout)

0 comments on commit 8299fbb

Please sign in to comment.