import models class DB(object): ... def model_for_table(self, table_name, **namespace): introspection = db.connections[self.alias].introspection cursor = db.connections[self.alias].cursor() namespace.update({ '__module__': __name__, 'Meta': type("Meta", (object,), {'db_table': table_name}), '_adhocdb_alias': self.alias, }) for row in introspection.get_table_description(cursor, table_name): rname, rtype, _, _, _, _, nullok = row try: classname = introspection.DATA_TYPES_REVERSE[rtype] fieldclass = getattr(models, classname) except (KeyError, AttributeError): fieldclass = models.TextField namespace[rname] = fieldclass(null=nullok) return type(table_name, (models.Model,), namespace)