Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango fixtures primary key error, need natural keys solution
    text
    copied!<p>So I have a Film model that holds a list of Actors model in a many to many field:</p> <pre><code>class Person(models.Model): full = models.TextField() short = models.TextField() num = models.CharField(max_length=5) class Film(models.Model): name = models.TextField() year = models.SmallIntegerField(blank=True) actors = models.ManyToManyField('Person') </code></pre> <p>I'm trying to load some initial data from json fixtures, however the problem I have is loading the many to many actors field. For example I get the error:</p> <p>DeserializationError: [u"'Anna-Varney' value must be an integer."]</p> <p>with these fixtures:</p> <pre><code> { "pk": 1, "model": "data.Film", "fields": { "actors": [ "Anna-Varney" ], "name": "Like a Corpse Standing in Desperation (2005) (V)", "year": "2005" } </code></pre> <p>while my actors fixture looks like this:</p> <pre><code> { "pk": 1, "model": "data.Person", "fields": { "full": "Anna-Varney", "num": "I", "short": "Anna-Varney" } } </code></pre> <p>So the many to many fields must use the pk integer, but the problem is that the data isn't sorted and for a long list of actors I don't think its practical to manually look up the pk of each one. I've been looking for solutions and it seems I have to use natural keys, but I'm not exactly sure how to apply those for my models. </p> <p>EDIT: I've changed my models to be:</p> <pre><code>class PersonManager(models.Manager): def get_by_natural_key(self, full): return self.get(full=full) class Person(models.Model): objects = PersonManager() full = models.TextField() short = models.TextField() num = models.CharField(max_length=5) def natural_key(self): return self.full </code></pre> <p>But I'm still getting the same error</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload