- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
def export_to_csv(model, fields=None, related_models=[]):
def export(request):
meta = model._meta
queryset = model.objects.all()
if fields is not None:
field_names = fields
elif 'Shops' in related_models and 'Spots' in related_models:
field_names = [field.name for field in Shops._meta.fields] +\
[field.name for field in Spots._meta.fields]
elif 'Products' in related_models and 'Spots' in related_models:
field_names = [field.name for field in Products._meta.fields] +\
[field.name for field in Spots._meta.fields]
else:
field_names = []
for field in meta.fields:
if not field.name in FORBIDDEN_FIELDS:
field_names.append(field.name)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta)
response.write(u'\ufeff'.encode('utf8'))
writer = csv.writer(response, delimiter=',', lineterminator='\n', quoting=csv.QUOTE_ALL, dialect='excel')
writer.writerow(field_names)
if len(related_models) == 0:
for obj in queryset:
row = writer.writerow([getattr(obj, field) for field in field_names])
elif 'Shops' in related_models and 'Spots' in related_models:
shops_fields = [field.name for field in Shops._meta.fields]
contact_fields = [field.name for field in Spots._meta.fields]
for obj in queryset:
row = []
if obj.Shops is not None:
row += [getattr(obj.Shops, field) for field in shops_fields]
else:
row += ['' for field in shops_fields]
if obj.Contact is not None:
row += [getattr(obj.Contact, field) for field in contact_fields]
else:
row += ['' for field in contact_fields]
writer.writerow(row)
elif 'Products' in related_models and 'Spots' in related_models:
products_fields = [field.name for field in Products._meta.fields]
contact_fields = [field.name for field in Spots._meta.fields]
for obj in queryset:
row = []
if obj.Products is not None:
row += [getattr(obj.Products, field) for field in products_fields]
else:
row += ['' for field in products_fields]
if obj.Contact is not None:
row += [getattr(obj.Contact, field) for field in contact_fields]
else:
row += ['' for field in contact_fields]
writer.writerow(row)
return response
return export
В юности нагородила вот такую портянку для экспорта в csv связных между собой таблиц. Связка данных на уровне DAO-шки (в терминологии Джанго - Managers)? Пфф... Только инжект if-else с копипастой связки данных, только хардкор!