zen11625 zen11625 - 1 year ago 92
Python Question

How to use some field instead of primary keys in Django 1.6 model fixtures?

I need to dump and load fixtures of model objects without usage of primary keys. The model is flat. I know about natural keys in Django, spent a lot of time reading the documentation, but all documentation has solutions only for usage natural keys instead of relations (fk / m2m). This is totally not what I need.

I need something like this:


class Template(models.Model):
name = models.CharField(_('name'), max_length=100)
content = models.TextField(_('content'), blank=True)

def natural_key(self):
return (self.name,)


"pk": null,
"model": "dbtemplates.Template",
"fields" {
"content": "",
"name": "product"

And after command

./manage.py <SOME_LOADDATA_COMMAND> fixture1.json --natural

I need to update my Template object which has name "product" or insert it.

The standard Django commands don't do this. Please, help me with any solution. Maybe there are some libraries for this? I'm confusing.

Django 1.6. Python 2.7

Answer Source

Django 1.6 does not provide a way to dump data with natural primary keys, but Django 1.7 does.

Unfortunately, the use_natural_primary_keys keyword argument is not supported by the base Django 1.6 serializer: https://github.com/django/django/blob/1.6.11/django/core/serializers/base.py#L20

So I suggest you either upgrade to django 1.7 (which I totally understand is not always possible) or you write your own serializer, drawing inspiration from the base Django 1.7 serializer (https://github.com/django/django/blob/1.7.11/django/core/serializers/base.py).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download