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.
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.
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
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)