djangodjango-fixtures

Update database records from data fixtures


How can I update an already populated Django database with records from a data fixture (or other serialized records)?

I know I can use Django data fixtures to provide initial data. Can I use the same already written features to update the database from data fixtures (or similar serialized data like a JSON document)?

The “insert or update from serialised data” operation should be idempotent:

Specifically, can I update existing rows by specifying pk=null and using natural keys?

How can I use the existing Django “load data” features (whether loaddata or something else similar in Django), to read serialised data, insert records if they don't exist and update them if they already exist?


Solution

  • Yes, you can with loaddata:

    python3 -m django loaddata path/to/fixture/some_new_data.json
    

    BUT:

    Depending on the nature of your data, it may be better to use a data migration in South. A data migration might be good when you're setting just a couple of values for lots of records (eg, changing the default of a field, or filling in an empty field with data). A data migration also lets you apply some checks/logic to things, via Python, so that you can target which records you update, or update different records in different ways, rather than writing lots of fixtures. If, however, you want to load in a ton of new records, a fixture would make more sense.