from django.contrib import adminfrom .models import Order,OrderItemfrom django.http import HttpResponseimport datetime# Register your models here.import csvdef export_to_csv(modeladmin, request, queryset): opts=modeladmin.model._meta response=HttpResponse(content_type='text/csv') response['Content-Disposition']='attachment;filename={}.csv'.format(opts.verbose_name) writer=csv.writer(response) fields = [field for field in opts.get_fields() if not field.many_to_many and not field.one_to_many] writer.writerow([field.verbose_name.encode('utf-8') for field in fields]) for obj in queryset: data_row=[] for field in fields: value=getattr(obj,field.name) if isinstance(value,datetime.datetime): value=value.strftime('%d/%m/%Y') data_row.append(value) writer.writerow(data_row) return responseexport_to_csv.short_description = '导出ESV'class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product']class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'email', 'address', 'postal_code', 'city', 'paid', 'created', 'updated'] list_filter = ['paid', 'created', 'updated'] inlines = [OrderItemInline] actions = [export_to_csv]admin.site.register(Order, OrderAdmin)