One of the things that bugs me about Django fixtures is that you've got to specify every model's primary key. Is there any way to create fixtures without having to specify a primary key for each row?
4 Answers
Use "pk: null" instead of "pk: 1" (or whatever), which will result in the PK being set to None, and when the object is saved a primary key will be assigned.
This works for YAML at least, I'm guessing you're using that if you are creating by hand.
-
32You have to be careful when using pk-less fixture. When recalling loaddata, it will try to add new entries instead of overriding existing ones. Nov 27, 2012 at 22:16
-
1spookylukey or @Danosaure Is there a way to generate "pk: null" fixtures using manage.py dumpdata? I'm consolidating two DB's with identical schemas and am working out how to do this with dumpdata/loaddata Feb 18, 2013 at 15:58
-
1@BenRoberts The issue with pk:null is that you may end up with duplicates. I usually just dumpdata and vi the file to do this kind of stuff. Mar 9, 2013 at 10:33
-
1How to use this method but with natural keys together? I want to use natural key as object id when loaddata it. The official Django documentation about natural keys is disgusting :( Aug 18, 2016 at 5:41
-
1@zen11625 - if there is insufficient documentation in Django, please file a bug - code.djangoproject.com - doc issues are regarded as bugs. Aug 21, 2016 at 11:55
You should have a look at Natural Keys if you're wiling to add relation without using pk's
https://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-app-label-app-label-app-label-model
-
8Unfortunately, the docs on natural keys fails to mention the pk=null trick used above. You need both pk=null and natural keys to have a fully pk-less fixture.– CerinFeb 27, 2012 at 1:58
-
Unfortunately that link no longer works. Here is one which works today, let's see if it lasts more than 3 years: docs.djangoproject.com/en/dev/ref/django-admin/… Oct 2, 2014 at 23:10
A friend of mine suggested the fixture
module: http://farmdev.com/projects/fixture/
-
1That seems like a fair stack of boilerplate code to work with. My workflow for generating data for testing is often to use the admin interface to create data, then use django-test-utils' makefixture to dump it out to a file, and then (if necessary) nullify any pk entries. Apr 18, 2012 at 6:56
If you check out the manage.py dumpdata
command, you will see some options called --natural-foreign
, --natural-primary
, etc. If you look at the output you can see that the objects are dumped without using primary keys or foreign keys.