Exporting items from a model to CSV Django / Python

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

    I use this on my code. A function called from view. It automatically get model fields to make columns. You can also customize the field list you want to export.

    Function

    import csv
    
    from django.http import HttpResponse
    
    from .models import Books
    
    
    def export_qs_to_csv(model_class = None, qs = None, field_names = None):
        if model_class and not qs:
            qs = model_class.objects.all()
        if qs and not model_class:
            model_class = qs.model
    
        meta = model_class._meta
        if not field_names:
            field_names = [field.name for field in meta.fields]
    
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
        writer = csv.writer(response)
    
        writer.writerow(field_names)
        for obj in qs:
            row = writer.writerow([getattr(obj, field) for field in field_names])
    
        return response
    

    Usage

    @user_passes_test(lambda u: u.is_superuser)
    def export_books(request):
        return export_qs_to_csv(model_class = Books)
        # or
        return export_qs_to_csv(qs = Books.objects.filter(published = True))
        # or
        return export_qs_to_csv(
            qs = Books.objects.filter(published = True),
            field_names = [
                "title",
                "price",
                "publishing_date",
            ]
            )
    

    Original answer

    It works, and it needs only to define model class in model_class variable. This Django view let use downloads CSV. CSV name is Django_app.model_name.csv.

    import csv
    
    from django.http import HttpResponse
    
    from .models import Trade
    
    
    def export_to_csv(request):
        # The only line to customize
        model_class = Trade
    
        meta = model_class._meta
        field_names = [field.name for field in meta.fields]
    
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
        writer = csv.writer(response)
    
        writer.writerow(field_names)
        for obj in model_class.objects.all():
            row = writer.writerow([getattr(obj, field) for field in field_names])
    
        return response
    

提交回复
热议问题