arjun
arjun

Reputation: 2421

Django models: dynamically generate model field

I have the following file say prof.xml

<include>
  <param name="xxx" value="yyy"/>
  <param name="mmm" value="nnn"/>
</include>

Now I want to create django model where the model should look like this

class prof:
   xxx= models.CharField(verbose_name="XXX",max_length=45)
   mmm = models.CharField(verbose_name="YYY",max_length=100)

ie The model fields should have the names that are param names in the xml file and the values in the xml file should be inserted into the database. How can this be done?

I have done something like this to get the param name from the xml but I dunno how to create model field names out of that.

 import os
 files = [file for file in os.listdir(os.path.join(path,'prof.xml')) if                    os.path.isfile(file)]
 for file in files:
    f = open((os.path.join(path,'prof.xml')),'r')
    for line in f.readlines():
        pos1 = line.find("param name")
        pos2 = line.find("value")
        if pos1>=0 and pos2>=0:
            field_name=line[pos1+12:pos2-2]

Upvotes: 0

Views: 208

Answers (2)

acjay
acjay

Reputation: 36521

First of all, you shouldn't be parsing your XML by hand. That's a recipe for disaster. Use a library.

Also, I'm going to second Rohan's advice on not trying to create your models dynamically, but it is possible. I do it in tests for libraries, as seen here, but I've never tried it for making permanent tables. I haven't tested this, but something like this might work:

from django.core.management import call_command
from django.db import models

def create_new_model(name, fields):
    new_model = type(name, models.Model, fields)
    models.register_models('myapp', new_model)
    call_command('syncdb')

If anyone's crazy enough to try this, please comment and let me know how it goes.

Upvotes: 1

Rohan
Rohan

Reputation: 53326

I'm not sure you can do that dynamically, as after creating model, you need to syncdb to create appropriate tables etc.

May be you could change your design a bit and have a model with keyand value fields.

class DataContainer(models.Model):
   key = models.CharField(verbose_name="key",max_length=45)
   value = models.CharField(verbose_name="value",max_length=100)

And have ManyToMany or ForeignKey relation with your model like:

class SomeModel(models.Model):
    data = models.ManyToManyField(DataContainer)

Upvotes: 2

Related Questions