I'm trying to write a view in Django to export my model data in a csv file.
The problem is that I can't figure out how to exclude related fields. Currently, when I run model._meta.get_fields(), the function returns the model's fields and the related model's field, so my view throws an error when I use getattr() using the related field's name.
I tried using .is_related() to exclude related fields, but that also excludes the model fields (like ForeignKey).
When I call the field name, I can see the class name is ManyToOneRel, but I can't figure out how to access that attribute.
Does anyone know how to exclude related fields or figure out if a field is a related model's field?
My view is below.
Thanks to anyone that can help!
class CSVExportView(View):
template_name = 'medrec_v2/csv_export.html'
def get(self, request, *args, **kwargs):
model_list = [m for m in apps.app_configs['medrec_v2'].models if '_' not in m ]
# print(model_list)
context = {'model_list':model_list}
return render(request, self.template_name, context)
def post(self, request, *args, ):
model_name = request.POST.get("model-sel")
model = apps.get_model(app_label='medrec_v2',model_name=model_name)
content_type = 'text/csv'
datecode = datetime.today().strftime('%y%m%d')
file_name = f'{datecode}_medrecv2_{model_name}.csv'
response = HttpResponse(content_type = content_type)
response['Content-Disposition'] = f'attachment; filename="{file_name}"'
header = [f.name.split('.')[-1] for f in model._meta.get_fields() if f.is_relation == False]
print(header)
writer = csv.writer(response)
writer.writerow(header)
i=0
for instance in model.objects.all():
row = []
for field in instance._meta.get_fields(include_parents=False):
if field.is_relation == False:
val = getattr(instance, field.name)
if val is None:
val = ''
row.append(val)
writer.writerow(row)
return response