0

I can get all the values from the database for a particular Django model in Python using something like

a = Attorney.objects.all().values_list()
print(a)

What command would I use to make a similar query but for all the column names in the database? Also, how would I append all the values returned by Attorney.objects.all().values_list() to a list that I could then iterate over?

Nicole Marie
  • 159
  • 2
  • 12
  • possible duplicate of [this](http://stackoverflow.com/questions/3106295/django-get-list-of-model-fields) and [this](http://stackoverflow.com/questions/3647805/get-models-fields-in-django) – algrebe Sep 23 '16 at 18:21

1 Answers1

0

If I understand correctly, I think something like the following would do what you're asking about.

import django.apps
models = django.apps.apps.get_models()
for model in models:
    field_names = [f.attname for f in model._meta.get_fields()]
    for fields in model.objects.values_list(*field_names):
        do_something_with_the_fields(fields)

This seems like an odd thing to want Django to do for you. What are you trying to accomplish by getting all the tables and field names django is aware of?

Edit based on further explanation in comments

To dump a table all columns of a table to a CSV, it's probably easiest to introspect the cursor's returned column metadata from the database. There's not much reason to use Django's model definitions in this case:

import csv
from django.db import connection

def dump_table_to_csv(db_table, io):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM %s" % db_table, [])
        rows = cursor.fetchall()
        writer = csv.writer(io)
        writer.writerow([i[0] for i in cursor.description])  # http://stackoverflow.com/a/9752485
        for row in rows:
            writer.writerow(row)


witb open('path/to/myfile.csv', 'wb') as f:
    dump_table_to_csv(django_model._meta.db_table, f)
Lucas Wiman
  • 10,021
  • 2
  • 37
  • 41
  • I want to be able to auto populate an Excel spreadsheet's headers with the column names from my database, for exporting data. not sure if this is the best way to do it but I assume it could be helpful if I got the column names directly from the db – Nicole Marie Sep 23 '16 at 19:42
  • You might try looking at django-import-export, which will probably do exactly what you want out of the box: https://github.com/django-import-export/django-import-export I also expanded the answer to include a somewhat simpler solution that's a bit more independent of Django. – Lucas Wiman Sep 24 '16 at 03:37