Exporting items from a model to CSV Django / Python

前端 未结 9 2046
死守一世寂寞
死守一世寂寞 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:39

    Depending on the scenario - you may want to have a CSV of your model. If you have access to the Django Admin site, you can plug in a generic action for any model displayed as a list (google: django admin actions)

    http://djangosnippets.org/snippets/790/

    If you're operating with a console (python manage.py ...), you can use such a script, which I just used:

    (place it in: yourapp/management/commands/model2csv.py)

    """
     Prints CSV of all fields of a model.
    """
    
    from django.core.management.base import BaseCommand, CommandError
    import csv
    import sys
    
    class Command(BaseCommand):
        help = ("Output the specified model as CSV")
        args = '[appname.ModelName]'
    
        def handle(self, *app_labels, **options):
            from django.db.models import get_model
            app_name, model_name = app_labels[0].split('.')
            model = get_model(app_name, model_name)
            field_names = [f.name for f in model._meta.fields]
            writer = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
            writer.writerow(field_names)
            for instance in model.objects.all():
                writer.writerow([unicode(getattr(instance, f)).encode('utf-8') for f in field_names])
    

    This does not catch any exceptions etc., but as an Admin you won't cause them to be raised, right?

    Use it like:

    ./manage.py model2csv my_ecommerce.Product > products.csv
    

提交回复
热议问题