Exporting items from a model to CSV Django / Python

前端 未结 9 2039
死守一世寂寞
死守一世寂寞 2021-02-03 09:52

I\'m fairly new to django and Python and want to be able to export a list of items in my model i.e products. I\'m looking at the documentation here - https://docs.djangoproject.

9条回答
  •  执念已碎
    2021-02-03 10:27

    Here is a potential solution, based on @tomasz-gandor 's answer, but updated to 2020:

    """
     Prints CSV of all fields of a model.
    """
    
    import csv
    from django.core.management.base import BaseCommand, CommandError
    
    
    class Command(BaseCommand):
        help = ("Output the specified model as CSV")
    
    
        def add_arguments(self, parser):
            parser.add_argument('model',
                                nargs=1,
                                type=str,
                                help='Model name to export, like  or "members.Member"')
            parser.add_argument('outfile',
                                nargs=1,
                                type=str,
                                help='Save path, like  or "/data/members.csv"')
    
    
        def handle(self, *app_labels, **options):
            from django.apps import apps
            app_name, model_name = options['model'][0].split('.')
            model = apps.get_model(app_name, model_name)
            field_names = [f.name for f in model._meta.fields]
            writer = csv.writer(open(options['outfile'][0], 'w'), quoting=csv.QUOTE_ALL, delimiter=',')
            writer.writerow(field_names)
            for instance in model.objects.all():
                writer.writerow([str(getattr(instance, f)) for f in field_names])
    

    Can easily be used with:

    python manage.py model2csv members.Member /data/members_export.csv

提交回复
热议问题