- July 13, 2007
- orm dynamic-model
- 3 (after 3 ratings)
This snippet proposes a solution for pre-exisiting database tables that have no counterpart in your django application models.py module.
My use case was a comercial systems where pricing tables were created on-the-fly as a result of a stored procedure's execution inside the database. These pricing tables had no counterpart class model. Therefore, to access these tables from Python code you had to bypass Django's ORM and use plain-old SQL through cursos.execute().
This snippet's strategy is to create a (model) class on the fly and inject that class inside models.py namespace. After that you can use the generated class and Django's ORM machinery to access the tables, as if they were created by syncdb.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
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())
More like this
- "Magic Link" Management Command by webology 1 month, 2 weeks ago
- Closest ORM models to a latitude/longitude point by simonw 1 month, 2 weeks ago
- Log the time taken to execute each DB query by kennyx46 1 month, 2 weeks ago
- django database snippet by ItsRLuo 1 month, 3 weeks ago
- Serialize a model instance by chriswedgwood 2 months, 3 weeks ago