1

I have set up a Django app that queries from a PostgreSQL database. Exporting all the data within a model seems relatively straight forward but what if I wanted to export only the data from a returned queryset.

Currently I'm managing this by having a button on my page and changing the url when the user wishes to export data. The code within the view that I'm rendering is as follows.

def export_data(request,pk):
    resource_class = MDPResource()
    queryset = MDP.objects.filter(mdp_id=pk)
    dataset = person_resource.export(queryset)
    response = HttpResponse(dataset.csv, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="mdpbasic.csv"'
    return response

However, this means that I'm going to be making one query when the user initially opens the page and then a second query (in effect 2 extra) when the user wishes to export the data which I have already queried for in the previous view.

Moreover, in a section of my page I'm also using Q models for complex filtering. The above method is not sufficient for exporting data in that case (I don't want to have to reconstruct the query).

I also do not want to have to write the data to a file (if I can help it) because then that raises the issue of having to delete it using os once the user has exported their data.

Generating CSV file with Django (dynamic content)

I have already checked out this question but I'm not sure how passing a dictionary to a urlpattern works and it still seems as though the query is being made one more time anyways (still one less than my current method).

I don't know if I should be checking out apps for this particular purpose. I've looked into a couple such as django-queryset-csv and django-import-export but none of them seem to do what I've mentioned.

django: export current queryset to csv by button click in browser

I've seen this example that makes use of class-based views but I wanted to see if there was a way to do it with function-based views so I don't have to migrate all my views to class-based ones.

Sharpfawkes
  • 549
  • 1
  • 8
  • 15
  • I'm not sure why you think this is a problem. Each request is separate, so yes you will need to make a new query for the export page. Why does this concern you? – Daniel Roseman Jun 27 '19 at 09:40
  • 1
    If the query is for a large amount of data which is going to take time to execute then I'm assuming it would be a problem? If this is the way everyone does it then I guess I could just go with it and see if there was a way to further refine my queries. It just seems unfortunate that I have to query the data again when I already have it available and the only new parameter is not something that will affect the data but a decision by the user to download the content. – Sharpfawkes Jun 27 '19 at 11:34

0 Answers0