Skip to content

Instantly share code, notes, and snippets.

@skywodd
Created April 18, 2018 15:54
Show Gist options
  • Save skywodd/6886e3b559c644a2fc2dc327311d5753 to your computer and use it in GitHub Desktop.
Save skywodd/6886e3b559c644a2fc2dc327311d5753 to your computer and use it in GitHub Desktop.
[Django 2.0 management command] Export all data related to the given user.
"""
Export all data related to the given user.
"""
from django.contrib.auth.models import User
from django.core.serializers import serialize
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Export all data related to the given user'
def serialize_model(self, instance):
return serialize('yaml', [instance], indent=2,
use_natural_foreign_keys=True,
use_natural_primary_keys=True)
def add_arguments(self, parser):
parser.add_argument('user_id', help='Target user ID', type=int)
def handle(self, *args, **options):
user_id = options['user_id']
fields = User._meta.get_fields(include_hidden=True)
related_fields = filter(lambda f: f.is_relation, fields)
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
raise CommandError('No user found with ID={}'.format(user_id))
output = []
output.append(self.serialize_model(user))
for relation in related_fields:
model = relation.related_model
instances = model.objects.filter(**{relation.remote_field.name: user_id})
for instance in instances:
output.append(self.serialize_model(instance))
self.stdout.write("---\n")
self.stdout.write('\n\n'.join(output))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment