def handle(self, *args, **options): serialize_me = [] seen = set() error_text = ('%s\nTry calling dump_object with --help argument or ' + 'use the following arguments:\n %s' % self.args) try: # verify input is valid try: (app_label, model_name) = options['model'].split('.') except AttributeError: raise CommandError("Specify model as `appname.modelname") query = options['query'] ids = options['ids'] if options['order']: options['order'] = json.loads(options['order']) ignore = [] if options['ignore']: ignore = json.loads(options['ignore']) related_ignore = [] if options['related_ignore']: related_ignore = json.loads(options['related_ignore']) if ids and query: raise CommandError(error_text % 'either use query or id list, not both') if not (ids or query): raise CommandError(error_text % 'must pass list of --ids or a json --query') except IndexError: raise CommandError(error_text % 'No object_class or filter clause supplied.') except ValueError as e: raise CommandError( error_text % "object_class must be provided in the following format: app_name.model_name" ) except AssertionError: raise CommandError(error_text % 'No filter argument supplied.') dump_me = loading.get_model(app_label, model_name) if query: objs = dump_me.objects.filter(**json.loads(query)) else: if ids[0] == '*': objs = dump_me.objects.all() else: try: parsers = int, long, str except NameError: parsers = int, str for parser in parsers: try: objs = dump_me.objects.filter(pk__in=map(parser, ids)) except ValueError: pass else: break else: objs = [] if options.get('kitchensink'): fields = get_all_related_objects(dump_me) # if there are no related ignores for this model include the field # or if this related field is not in the related ignores include the field related_fields = [rel.get_accessor_name() for rel in fields if model_name not in related_ignore or rel.name not in related_ignore[model_name]] for obj in objs: for rel in related_fields: try: if hasattr(getattr(obj, rel), 'all'): add_to_serialize_list(getattr(obj, rel).all(), serialize_me, seen, ignore=ignore) else: add_to_serialize_list([getattr(obj, rel)], serialize_me, seen, ignore=ignore) except FieldError: pass except ObjectDoesNotExist: pass add_to_serialize_list(objs, serialize_me, seen, prepend=True, ignore=ignore) if options.get('follow_fk', True): serialize_fully(serialize_me, seen, ignore) else: # reverse list to match output of serializez_fully serialize_me.reverse() natural_foreign = (options.get('natural', False) or options.get('natural_foreign', False)) natural_primary = (options.get('natural', False) or options.get('natural_primary', False)) data = serialize(options.get('format', 'json'), [o for o in serialize_me if o is not None], indent=4, use_natural_foreign_keys=natural_foreign, use_natural_primary_keys=natural_primary) data = reorder_json( json.loads(data), options.get('order', []), ) self.stdout.write(json.dumps(data, indent=4))
def dump_object(model, query, ids, order=[], ignore=[], related_ignore={}, additional_serialization_objects_fnc=None, format='json', kitchensink=True, follow_fk=True, natural=False, natural_foreign=False, natural_primary=False): serialize_me = [] seen = set() error_text = ('Error\n') try: # verify input is valid try: (app_label, model_name) = model.split('.') except AttributeError: raise CommandError("Specify model as `appname.modelname") if ids and query: raise CommandError(error_text % 'either use query or id list, not both') if not (ids or query): raise CommandError(error_text % 'must pass list of --ids or a json --query') except IndexError: raise CommandError(error_text % 'No object_class or filter clause supplied.') except ValueError as e: raise CommandError( error_text % "object_class must be provided in the following format: app_name.model_name" ) except AssertionError: raise CommandError(error_text % 'No filter argument supplied.') dump_me = loading.get_model(app_label, model_name) if query: objs = dump_me.objects.filter(**json.loads(query)) else: if ids[0] == '*': objs = dump_me.objects.all() else: try: parsers = int, long, str except NameError: parsers = int, str for parser in parsers: try: objs = dump_me.objects.filter(pk__in=map(parser, ids)) except ValueError: pass else: break if kitchensink: fields = get_all_related_objects(dump_me) # if there are no related ignores for this model include the field # or if this related field is not in the related ignores include the field related_fields = [rel.get_accessor_name() for rel in fields if model_name not in related_ignore or rel.name not in related_ignore[model_name]] generic_foreign_key_fields = get_all_generic_foreign_keys(dump_me) for field in generic_foreign_key_fields: if model_name not in related_ignore or field.name not in related_ignore[model_name]: related_fields.append(field.name) for obj in objs: for rel in related_fields: try: if hasattr(getattr(obj, rel), 'all'): add_to_serialize_list(getattr(obj, rel).all(), serialize_me, seen, ignore=ignore) else: add_to_serialize_list([getattr(obj, rel)], serialize_me, seen, ignore=ignore) # allow user to add additional data apart from standard foreign keys if additional_serialization_objects_fnc and \ callable(additional_serialization_objects_fnc): extra_objs = additional_serialization_objects_fnc(getattr(obj, rel)) if extra_objs: add_to_serialize_list(extra_objs, serialize_me, seen, ignore=ignore) except FieldError: pass except ObjectDoesNotExist: pass add_to_serialize_list(objs, serialize_me, seen, prepend=True, ignore=ignore) if follow_fk: serialize_fully(serialize_me, seen, ignore, additional_serialization_objects_fnc) else: # reverse list to match output of serializez_fully serialize_me.reverse() natural_foreign = (natural or natural_foreign) natural_primary = (natural or natural_primary) if format: if format == "json": data = CustomJsonSerializer().serialize( [o for o in serialize_me if o is not None], indent=4, use_natural_foreign_keys=natural_foreign, use_natural_primary_keys=natural_primary) else: data = serialize(format, [o for o in serialize_me if o is not None], indent=4, use_natural_foreign_keys=natural_foreign, use_natural_primary_keys=natural_primary) data = reorder_json( json.loads(data), order, ) return json.dumps(data, indent=4) # return unserialized objs return [o for o in serialize_me if o is not None]
def handle(self, *args, **options): error_text = ('%s\nTry calling dump_object with --help argument or ' + 'use the following arguments:\n %s' % self.args) try: # verify input is valid try: (app_label, model_name) = options['model'].split('.') except AttributeError: raise CommandError("Specify model as `appname.modelname") query = options['query'] ids = options['ids'] if ids and query: raise CommandError(error_text % 'either use query or id list, not both') if not (ids or query): raise CommandError(error_text % 'must pass list of --ids or a json --query') except IndexError: raise CommandError(error_text % 'No object_class or filter clause supplied.') except ValueError: raise CommandError( error_text % "object_class must be provided in the following format: app_name.model_name" ) except AssertionError: raise CommandError(error_text % 'No filter argument supplied.') dump_me = loading.get_model(app_label, model_name) if query: objs = dump_me.objects.filter(**json.loads(query)) else: if ids[0] == '*': objs = dump_me.objects.all() elif 'limit:' in ids[0]: try: limit = int(ids[0].replace('limit:', '')) objs = dump_me.objects.all()[:limit] except: raise CommandError( 'Recheck the command it should be limit:N, N is the limit.' ) else: try: parsers = int, long, str except NameError: parsers = int, str for parser in parsers: try: objs = dump_me.objects.filter(pk__in=map(parser, ids)) except ValueError: pass else: break if options.get('kitchensink'): fields = get_all_related_objects(dump_me) related_fields = [rel.get_accessor_name() for rel in fields] for obj in objs: for rel in related_fields: try: if hasattr(getattr(obj, rel), 'all'): add_to_serialize_list(getattr(obj, rel).all()) else: add_to_serialize_list([getattr(obj, rel)]) except FieldError: pass except ObjectDoesNotExist: pass add_to_serialize_list(objs) if options.get('follow_fk', True): serialize_fully() else: # reverse list to match output of serializez_fully serialize_me.reverse() natural_foreign = (options.get('natural', False) or options.get('natural_foreign', False)) natural_primary = (options.get('natural', False) or options.get('natural_primary', False)) self.stdout.write( serialize(options.get('format', 'json'), [o for o in serialize_me if o is not None], indent=4, use_natural_foreign_keys=natural_foreign, use_natural_primary_keys=natural_primary)) # Clear the list. Useful for when calling multiple # dump_object commands with a single execution of django del serialize_me[:] seen.clear()
def handle(self, *args, **options): error_text = ( "%s\nTry calling dump_object with --help argument or " + "use the following arguments:\n %s" % self.args ) try: # verify input is valid try: (app_label, model_name) = options["model"].split(".") except AttributeError: raise CommandError("Specify model as `appname.modelname") query = options["query"] ids = options["ids"] if ids and query: raise CommandError(error_text % "either use query or id list, not both") if not (ids or query): raise CommandError( error_text % "must pass list of --ids or a json --query" ) except IndexError: raise CommandError( error_text % "No object_class or filter clause supplied." ) except ValueError: raise CommandError( error_text % "object_class must be provided in the following format: app_name.model_name" ) except AssertionError: raise CommandError(error_text % "No filter argument supplied.") dump_me = loading.get_model(app_label, model_name) if query: objs = dump_me.objects.filter(**json.loads(query)) else: if ids[0] == "*": objs = dump_me.objects.all() else: try: parsers = int, long, str except NameError: parsers = int, str for parser in parsers: try: objs = dump_me.objects.filter(pk__in=map(parser, ids)) except ValueError: pass else: break if options.get("kitchensink"): fields = get_all_related_objects(dump_me) related_fields = [rel.get_accessor_name() for rel in fields] for obj in objs: for rel in related_fields: try: if hasattr(getattr(obj, rel), "all"): add_to_serialize_list(getattr(obj, rel).all()) else: add_to_serialize_list([getattr(obj, rel)]) except FieldError: pass except ObjectDoesNotExist: pass if options["count"] is not None: objs = objs.all()[: options["count"]] add_to_serialize_list(objs) if options.get("follow_fk", True): serialize_fully() else: # reverse list to match output of serializez_fully serialize_me.reverse() natural_foreign = options.get("natural", False) or options.get( "natural_foreign", False ) natural_primary = options.get("natural", False) or options.get( "natural_primary", False ) self.stdout.write( serialize( options.get("format", "json"), [o for o in serialize_me if o is not None], indent=4, use_natural_foreign_keys=natural_foreign, use_natural_primary_keys=natural_primary, ) ) # Clear the list. Useful for when calling multiple # dump_object commands with a single execution of django del serialize_me[:] seen.clear()