0

I have a values queryset of my values. how can convert it to a csv file.

Its important to export it by postgresql not python. because queryset have too many records.

vorujack
  • 1,778
  • 16
  • 22
  • Could you please elaborate, what do you mean by "exporting by postgresql not python"? You don't want to use python at all? You expect postgresql server to return CSV in response to a request made by your script written in python? – u354356007 Jul 30 '18 at 08:36
  • https://stackoverflow.com/questions/1517635/save-pl-pgsql-output-from-postgresql-to-a-csv-file – Brown Bear Jul 30 '18 at 09:05
  • you can do exporting data in django admin, If you don't have problem with django admin – Ali Jul 30 '18 at 09:22
  • 1
    I dont want to write a python loop and generate csv – vorujack Jul 30 '18 at 11:30

2 Answers2

0

after many search and test i found this solution

objects = query.values(field_list)
cursor = connection.cursor()
stdout = BytesIO()
cursor.copy_to(stdout,  "(" + unicode(objects.query) + ")", null="", sep=",")
csv = stdout.getvalue()

and postgresql generate csv automatically

vorujack
  • 1,778
  • 16
  • 22
0
import csv

query_set = django_query_set_you_have_made      

fields = ['Field1', 'Field2']

with open('my_file.csv', 'w') as file:
    write = csv.writer(file)
    write.writerow(fields)
    write.writerows(query_set)
David A
  • 141
  • 2
  • 10