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?
Asked
Active
Viewed 2.1k times
68
-
1are you using manage.py --dumpdata or writing them by hand? – Thomas Schreiber Sep 30 '09 at 19:04
4 Answers
99
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.

spookylukey
- 6,380
- 1
- 31
- 34
-
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. – Danosaure Nov 27 '12 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 – B Robster Feb 18 '13 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. – Danosaure Mar 09 '13 at 10:33
-
Thx @Danosaure. I ended up writing a quick python script that uses regex to do the trick. – B Robster Mar 11 '13 at 22:30
-
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 :( – Vladimir Chub Aug 18 '16 at 05:41
-
1@zen11625 - if there is insufficient documentation in Django, please file a bug - https://code.djangoproject.com/ - doc issues are regarded as bugs. – spookylukey Aug 21 '16 at 11:55
13
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

Eduardo
- 22,574
- 11
- 76
- 94
-
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. – Cerin Feb 27 '12 at 01:58
-
Unfortunately that link no longer works. Here is one which works today, let's see if it lasts more than 3 years: https://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-app-label-app-label-app-label-model – Jay Taylor Oct 02 '14 at 23:10
0
A friend of mine suggested the fixture
module: http://farmdev.com/projects/fixture/

David Wolever
- 148,955
- 89
- 346
- 502
-
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. – Matthew Schinckel Apr 18 '12 at 06:56