[Django]-Django: How do I get every table and all of that table's columns in a project?

4đź‘Ť

âś…

I dug in to the source to find this solution. I feel like there’s probably a better way, but this does the trick.

This first block gets all of the normal (non-m2m) tables and their columns

from django.db import connection
from django.apps import apps

table_info = []
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)
for model in apps.get_models():
    if model._meta.proxy:
        continue

    table = model._meta.db_table
    if table not in tables:
        continue

    columns = [field.column for field in model._meta.fields]
    table_info.append((table, columns))

This next block was the tricky part. It gets all the m2m field tables and their columns.

for model in apps.get_models():
    for field in model._meta.local_many_to_many:
        if not field.creates_table:
            continue

        table = field.m2m_db_table()
        if table not in tables:
            continue
        columns = ['id'] # They always have an id column
        columns.append(field.m2m_column_name())
        columns.append(field.m2m_reverse_name())
        table_info.append((table, columns))
👤Wes Winham

5đź‘Ť

Have you taken a look at manage.py ?

You can get boatloads of SQL information, for example to get all the create table syntax for an app within your project you can do:

python manage.py sqlall <appname>

If you type:

python manage.py help

You can see a ton of other features.

👤Bartek

0đź‘Ť

Have you looked into “manage.py dumpdata” and “manage.py loaddata”? They dump and load in json format. I use it to dump stuff from one site and overwrite another site’s database. It doesn’t have an “every database” option on dumpdata, but you can call it in a loop on the results of a “manage.py dbshell” command.

👤eruciform

Leave a comment