Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all table names in a Django app

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 
like image 456
jack Avatar asked Dec 04 '09 06:12

jack


People also ask

How can I see all tables in Django?

If you're interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), . tables (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.

How can I get full name in Django?

You can use {{full_name}} in your Django template. Also, if your user is authenticated you can use {{request. user. get_full_name}} in the template.

How do I get all rows in Django?

The idea is to use Django's annotate (which is basically running group_by ) to find all the instances that have more than one row with the same my_id and process them as Ned suggests. Then for the remainder (which have no duplicates), you can just grab the individual rows.

How does Django define table name in model?

A model's database table name is constructed by joining the model's “app label” – the name you used in manage.py startapp – to the model's class name, with an underscore between them.


Video Answer


1 Answers

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

Another user comments that this also works (also untested):

[ m._meta.db_table for c in apps.get_app_configs() for m in c.get_models() ] 

And yet another recommends reading this answer:

Django get list of models in application

like image 121
cethegeek Avatar answered Sep 27 '22 18:09

cethegeek