3

Following the Django docs on deserialization, in my models.py I've created the class:

class PersonManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)

class Person(models.Model):
    objects = PersonManager()
    name = models.CharField(max_length=30, unique=True, blank=False, null=False)

    def __unicode__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Person)

    def __unicode__(self):
            return self.title

I've also created a fixture for Person, "person.json",

[
    { 
        "pk": null,
        "model": "myapp.person", 
        "fields": {
            "name": "josh",
        }
     }
]

and for Book, "book.json",

[
    { 
        "pk": null,
        "model": "myapp.book", 
        "fields": {
            "title": "my book",
            "author": ["josh"]
        }
     }
]

The fixtures are saved in the 'fixtures' folder.

I then do python manage.py sql myapp and python manage.py syncdb, and then python manage.py loaddata persondata.json. This works. (I can see the entered data on the admin page and I get a good insert count message back.)

Then I do python manage.py loaddata bookdata.json and I get the following error message:

DeserializationError: [u"'[u'josh']' value must be an integer."]

How can that be? Why is Django insisting that I use an integer for the primary key, when I've declared the PersonManager? What have I missed?

(NB. This is all working fine when I give author pk directly as an integer.)

Ken
  • 30,811
  • 34
  • 116
  • 155
  • My bad, I meant to mark the other one as a duplicate of this. The other question had an accepted answer, so I wanted to make sure that this one had a reference to that. Removed flag, but here is the answered possible duplicate: http://stackoverflow.com/questions/12577446/django-natural-key-for-fixtures-give-deserialization-error – Gady Aug 28 '14 at 00:58

1 Answers1

1

Your manager method has the wrong name. It should be get_by_natural_key rather than get_by_unique_key.

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99