Get all table names in a Django app


Question

How to get all table names in a Django app?

I use the following code but it doesn't get the tables created by ManyToManyField

from django.db.models import get_app, get_models
app = get_app(app_name)
for model in get_models(app):
    print model._meta.db_table
1
35
1/20/2017 2:55:01 PM

Accepted Answer

from django.db import connection
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)

As seen in the syncdb command for manage.py.

In a comment below, years after the answer above, ThePhi says (I haven't tested it):

from django.apps import apps 
from django.contrib import admin 
from django.contrib.admin.sites import AlreadyRegistered 

app_models = apps.get_app_config('my_app').get_models()
63
11/9/2017 7:57:44 PM

The simplest answer, that still allows you to pick which app you want, is to modify your code with one extra argument "include_auto_created".

from django.db.models import get_app, get_models
app = get_app(app_name)
for model in get_models(app, include_auto_created=True):
    print model._meta.db_table

Obviously I got this by following celope's advice to read the syncdb source, so thanks for that - just documenting an exact answer that includes the app name as it was what I wanted and possibly others too in future.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon