首先,这是我用作指南的页面: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 解析为自然键,而不是尝试使用我定义的自然键检查数据库中是否存在该项目。我究竟做错了什么?