[Django]-How to Django dumpdata nested models in yaml

2👍

So I figured out how to handle the export/import.

To export to a proper yaml file format I did the following:

...
class Command(BaseCommand):

def handle(self, *args, **options):
    with open('result.yaml', 'w') as yaml_file:
        model = serializer.Meta.model
        json_object = []
        json_data = json.dumps(serializer(model_data).data)
        json_object.append(json.loads(json_data))

        yaml.dump(
            json_object,
            yaml_file,
            default_flow_style=False,
            allow_unicode=False,
            encoding=None
        )

This export to a proper yaml file.

Then to import the yaml file I did the following:

...
class Command(BaseCommand):
    def handle(self, *args, **options):
        with open('result.yaml', 'r') as yaml_file:
            yaml_list = yaml.load(yaml_file.read())
            for data in yaml_list:
                ...process file

And that’s it!

Leave a comment