views:

37

answers:

1

I'm attempting to construct a Django application that models an existing set of tables. These tables all have the same fields, plus custom fields per table. What I'm wanting to do is model this structure, and have records save to a particular table based on what table model they are attached to.

These tables can be created quite often, so it is unfeasible to construct new models per table.

Perhaps the code will demonstrate what I'm trying to do more clearly:



class CustomField(models.Model):
    column_name = models.CharField(max_length=100)
    description = models.CharField(max_length=255, blank=True, null=True)

class CustomData(models.Model):
    custom_field = models.ForeignKey(CustomField)
    value = models.CharField(max_length=100, blank=True, null=True)
    # value will always be a nullable varchar(100)

class Table(models.Model):
    table_name = models.CharField(max_length=255)
    name = models.CharField(max_length=100)
    custom_fields = models.ManyToManyField(CustomField)

class Record(models.Model):
    table = models.ForeignKey(Table)
    ... list of common fields omitted ...
    custom_values = models.ManyToManyField(CustomData)

When saving a new record that has a foreign key to 'table_1', I would like the eventual operation to be along the lines of insert into table_1 (..fields..) values (..field values..)

Is this possible? I guess I could hook into signals or the save method, but I'd like to find the simplest approach if such exists.

+1  A: 

You can create unmanaged models dynamically. You just need to create a dict mapping column names to the data values. Once you have that, you can do the following:

from django.db import models

# This is the dict you created, mapping column names to values
values = {col_1: value_1, col_2: value_2, col_3: value_3, ... }

# Create a dict defining the custom field types, eg {col_name: django_field}
attrs = dict((c, models.CharField(max_length=100, blank=True, null=True)) for c in values)

# Add a Meta class to define the table name, eg table_1
class Meta:
  app_label = myapp
  db_table = 'table_1'
  managed = False
attrs['Meta'] = Meta
attrs['__module__'] = 'path.to.your.apps.module'

DynamicModel = type('MyModel', (models.Model,), attrs)

# Save your data
DynamicModel.objects.create(**values)

Wrap this up in a function, and put it in your .save() method on Record. If you have any common fields, you can add them to attrs, or even better: create an abstract model with all the common fields and inherit that in the last line above instead of models.Model.

Will Hardy
This is exactly how I ended up implementing it, including the abstract base model for all the common data. Creating the extra fields that way is much better than how I was going to do it though. I was planning on using add_to_class (defined on ModelBase) but definitely won't now. Thank you.
Josh Smeaton