まず、これをまとめるためのガイドとして使用したページです: https://docs.djangoproject.com/en/dev/topics/serialization/
これが私のモデル定義です:
class LocationManager(models.Manager):
def get_by_natural_key(self, zip_code):
return self.get(zip_code=zip_code)
class Location(models.Model):
city = models.CharField('City', blank=True, null=True, max_length=50)
state = models.CharField('State', blank=True, null=True, max_length=2, choices=STATE_CHOICES)
zip_code = models.CharField('Zip Code', blank=False, null=False, max_length=9, unique=True)
date_added = models.DateField('Date Added')
objects = LocationManager()
def natural_key(self):
return self.zip_code
これは、逆シリアル化しようとしているシリアル化されたアイテムです。
{
"pk": 10259,
"model": "news.news",
"fields": {
"content": "some content",
"created_on": "2012-07-24T16:10:44.570",
"location": "99801",
"title": "Some title"
}
}
jsonを逆シリアル化しようとしているコード:
for news_obj in serializers.deserialize('json', news_json):
news_obj.save()
私が得るエラーは次のとおりです。
IntegrityError: insert or update on table "news" violates foreign key constraint "news_location_id_fkey"
DETAIL: Key (location_id)=(99801) is not present in table "location".
そのため、定義した自然キーを使用してアイテムがデータベースに存在するかどうかを確認しようとするのではなく、zip_code を自然キーとして解決しようとしているようです。私は何を間違っていますか?