如何获取 Django 应用程序中的所有表名?
我使用以下代码,但它没有得到由 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
最佳答案
from django.db import connection
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)
如 manage.py 的 syncdb 命令所示。
在下面的评论中,在上述答案多年后,ThePhi说(我还没有测试过):
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()
另一个用户评论说这也有效(也未经测试):
[ m._meta.db_table for c in apps.get_app_configs() for m in c.get_models() ]
还有一个建议阅读这个答案:
关于python - 获取 Django 应用程序中的所有表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1845293/