Binding pre-existing tables with dynamically created class models

 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

  1. Table Creation Using ORM Standalone by EliAndrewC 6 years, 2 months ago
  2. Ordered items in the database - alternative by Leonidas 6 years, 10 months ago
  3. Django Using Stored Procedure by iapain 7 years, 1 month ago
  4. FieldAccessForm (per-field user access for forms derived from models) by Killarny 5 years, 6 months ago
  5. Quick and dirty way to make dynamically available all tables of a database as models by henning 6 years, 11 months ago

Comments

rodsenra (on July 13, 2007):

I would like to thank Andrews Medina for the suggestion of posting this snippet here, and thank Rafael Sierra for improving the snippet to make it more general.

#

(Forgotten your password?)