def create_tp_model(table_name, table_schema, namespace): '''Function that creates a class dynamically and injects it into namespace. Usually namespace is an object that corresponds to models.py's in memory object. ''' template = ''' class %s(models.Model): %s class Meta: db_table = '%s' ''' exec template%(table_name, table_schema, table_name) in namespace # sample table_name = 'SampleTable' table_schema = """ price = models.DecimalField("Price", max_digits=10, decimal_places=3) product = models.ForeignKey('Product') """ # Usage from django.db import connection, get_introspection_module introspection_module = get_introspection_module() cursor = connection.cursor() # Use globals() if this code already runs in models.py # otherwise import models and use the module instance instead of globals(). create_tp_model(table_name, table_schema, globals())