Search code examples
djangodjango-modelsdjango-fixtures

Import data into Django model with existing data?


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?


Solution

  • 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()