'Django: Create fixtures without specifying a primary key?
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?
Solution 1:[1]
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
Solution 2:[2]
If you check out the manage.py dumpdata command, you will see some options called --natural-foreign, --natural-primary. If you look at the output you can see that the objects are dumped without using primary keys or foreign keys.
Solution 3:[3]
A friend of mine suggested the fixture module: http://farmdev.com/projects/fixture/
Solution 4:[4]
I had to deal with existing DB schema without possibility to change it, so I need a table with complex primary key or without it at all - but not with the serial one. What I did:
I've specified a primary_key=True to the field, which should not be unique at all and wrote overloaded method:
class ContraIndicationsMedicines(models.Model):
contra_indication = models.ForeignKey(ContraIndication, primary_key=True)
medicine = models.ForeignKey(Medicine)
def validate_unique(self, exclude=None):
pass
In fact, it worked for my needs, but there are more validations call inside django.contib.admin.* and not all the inlines e.t.c are guaranteed to work. That was the only solution I could implement... ((
Solution 5:[5]
natural primary key
With a natural primary key (where the model field option is set to "primary_key=True") you can easily leave out the specification of the primary key in your fixture. Django will automatically check for the natural primary key then and there is no risk of adding duplicate entries.
auto primary key (not manually defined pk)
When there is an automatic primary key the only option I see here is to dump the data and edit the entries with a script or set new entries' primary key to null as stated by @spookylukey.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | molecular |
| Solution 3 | David Wolever |
| Solution 4 | |
| Solution 5 | cyc8 |
