我有以下文件,即prof.xml
<include>
<param name="xxx" value="yyy"/>
<param name="mmm" value="nnn"/>
</include>现在我想创建django模型,模型应该如下所示
class prof:
xxx= models.CharField(verbose_name="XXX",max_length=45)
mmm = models.CharField(verbose_name="YYY",max_length=100)即模型字段的名称应该是xml文件中的参数名称,并且xml文件中的值应该插入到数据库中。如何做到这一点?
为了从xml中获取参数名,我做了一些类似的操作,但是我不知道如何从xml中创建模型字段名。
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]发布于 2013-02-28 14:55:19
我不确定你是否能动态地做到这一点,因为在创建模型之后,你需要同步数据库来创建合适的表等。
也许你可以稍微改变一下你的设计,拥有一个带有key和value字段的模型。
class DataContainer(models.Model):
key = models.CharField(verbose_name="key",max_length=45)
value = models.CharField(verbose_name="value",max_length=100)并与您的模型建立ManyToMany或ForeignKey关系,如:
class SomeModel(models.Model):
data = models.ManyToManyField(DataContainer)发布于 2013-02-28 15:45:44
首先,您不应该手动解析XML。这就是灾难的秘诀。使用库。
此外,我将赞同Rohan关于不要尝试动态创建模型的建议,但这是可能的。我在库as seen here的测试中这样做,但我从来没有尝试过用它来制作永久表。我还没有测试过,但是像这样的东西可能会起作用:
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')如果任何人疯狂到尝试这个,请评论并让我知道它的进展。
https://stackoverflow.com/questions/15129244
复制相似问题