-
Notifications
You must be signed in to change notification settings - Fork 133
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add management command to recover deleted attachments
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
onadata/apps/logger/management/commands/recover_deleted_attachments.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |