使用现有数据将数据导入Django模型? [英] Import data into Django model with existing data?

查看:139
本文介绍了使用现有数据将数据导入Django模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用在线表单构建工具(专门用于保险代理)。我们希望为客户提供的其中一个事情是预先制作普通产品(汽车,家庭,生活等)的预制表格,但仍可修改。



在正常情况下,我将简单地在我的开发环境中创建表单,然后创建一个包含这些表单的fixture,并在所有的活动站点上运行syncdb。不幸的是,这不是一个可能性,因为我们的一些客户已经创建了表单,这可能与我的主题中的主键有冲突。还有四个不同的相互关联的表,我正在寻找出口,但它都在我的 sqformbuilder 应用程序。


解决方案

有没有办法导出固定装置,但是可以将其灵活插入数据库的另一个运行副本? >在sebpiq的一些帮助下,我能够使用 South 自然键 json dumpdata



基本上它只是一个数据迁移使用转储json:

  datafdir = os.path.dirname(__ file__)
dataf = open(os.path.join(datafdir,'0002_mh_quote_form.data.json'),'r')
buildformfieldsjson = simplejson.loads(dataf.read())
form = BuiltForm .objects.get(pk = 1)
在buildformfieldsjson中的字段:
try:
builtfield = BuiltFormField.objects.get_by_natural_key(form,field ['fields'] ['fieldname'])
除了
builtfield = BuiltFormField(fieldname = field ['fields'] ['fieldname'],builtform = form)
在字段['fields']中的一部分:
如果part =='buildform':
continue
setattr(builtfield,part,field ['fields'] [part])
builtfield.save()


I'm working on an online form builder tool (specifically for insurance agents). One of the things we would like to offer our customers is to have pre-built forms for common products (auto, home, life, etc) be available by default, but still modifiable.

Under normal circumstances, I would simply create the forms in my development environment, then create a fixture containing these forms, and run syncdb on all the live sites. Unfortunately that isn't a possibility, as some of our customers already have created forms, which may conflict with the primary keys in my fixture. There are also four different inter-related tables that I am looking to export, but it is all in my sqformbuilder app.

Is there a way to export a fixture but allow it to be flexibly inserted into another running copy of the database?

解决方案

With some help from sebpiq, I was able to get this fixed using South, natural keys, and json dumpdata.

Basically it is just a data migration using the dumped json:

datafdir = os.path.dirname(__file__)
dataf = open(os.path.join(datafdir, '0002_mh_quote_form.data.json'), 'r')
builtformfieldsjson = simplejson.loads(dataf.read())
form = BuiltForm.objects.get(pk=1)
for field in builtformfieldsjson:
    try:
        builtfield = BuiltFormField.objects.get_by_natural_key(form, field['fields']['fieldname'])
    except:
        builtfield = BuiltFormField(fieldname=field['fields']['fieldname'], builtform=form)
    for part in field['fields']:            
        if part == 'builtform':
            continue
        setattr(builtfield, part, field['fields'][part])
    builtfield.save()  

这篇关于使用现有数据将数据导入Django模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆