Django Fixtures and Foreign Key Constraints

by on May 13, 2008 at 2:50 pm

This took me longer to debug than I would have liked. While trying to load a fixture for a unit test, I kept getting foreign key errors. The error message looked something like this:

Problem installing fixture ‘ads.json’: (1452, ‘Cannot add or update a child row: a foreign key constraint fails (`test_bv/monitor_monitor`, CONSTRAINT `created_by_id_refs_id_6f53f022` FOREIGN KEY (`created_by_id`) REFERENCES `auth_user` (`id`))’)

The solution was to modify my json file to ensure records that contained a foreign key reference were located after the record they referenced. So, in the example above, I had to place auth_user records at the top of the file since many records referred to it.

It would be nice if dumpdata would export json files such that they could be loaded (no foreign key constraints are broken). This may become my first contribution to the django project when I have some free time.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | Dave Naffziger's BlogDave & Iva Naffziger