Get all table names in a Django app

前端 未结 4 2009
谎友^
谎友^ 2020-12-24 12:16

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          


        
4条回答
  •  长情又很酷
    2020-12-24 12:45

    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

提交回复
热议问题