How to query for SQLite database column names in Python/Django?
<p>I can get all the values from the database for a particular Django model in Python using something like</p>

<pre><code>a = Attorney.objects.all().values_list()
print(a)
</code></pre>

<p>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 <code>Attorney.objects.all().values_list()</code> to a list that I could then iterate over?</p>

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

<pre><code>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)
</code></pre>

<p>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?</p>

<h2>Edit based on further explanation in comments</h2>

<p>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:</p>

<pre><code>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)
</code></pre>

python django sqlite django-queryset