Tuesday, October 19, 2010

Django List Installed Tables and Models

Get Database connection
# Django 1.2
from django.db import connections
connection = connections['default']

# Django 1.1.1<=
from django.db import connection

# Get Database tables
tables = connection.introspection.table_names()

# Get Database models
modelclasses = connection.introspection.installed_models(tables)

# Get Django model name and app name
for model in list(modelclasses):
    print model._meta.app_label, model._meta.module_name

# A better way to get Django models
from django.db.models.loading import get_models, get_app
get_app('app_label')  # returns an app class given a label
get_models()  # all models 
get_models(application)  # models belonging to app class

# Get a model from a string
from django.db import models
models.get_model(*"myapp.mymodel".split('.')) # returns model class

# Get all Python modules
import sys
sys.modules

http://www.slideshare.net/ubernostrum/django-in-depth?src=related_normal&rel=3017822


No comments: