这是我的问题。我正在尝试加载一些与另一个模型具有自然键关系的数据。
我修改了父模型以生成自然键。
我使用以下命令从旧数据库中导出了数据:
manage.py dumpdata resources.image -n --indent 4 > images.json
然后,我尝试使用以下命令导入到新数据库中:
manage.py loaddata images.json
在这一点上,我得到了错误:
IntegrityError: Problem installing fixtures: The row in table 'resources_image'
with primary key '340' has an invalid foreign key: resources_image.voyage_id contains
a value '41890' that does not have a corresponding value in voyage_voyage.id.
它试图查询voyage_voyage.id而不是get_by_natural_key函数中指定的voyage_voyage.voyage_id。我仔细检查了一下,灯具中的 key 在voyage_id字段中。下面是我的代码和示例夹具。
父模型:
# for parsing natural key
class VoyageManager(models.Manager):
def get_by_natural_key(self, voyage_id):
return self.get(voyage_id=voyage_id)
class Voyage(models.Model):
# for parsing natural key
objects = VoyageManager()
voyage_id = models.IntegerField("Voyage ID (can be empty)", null=True, blank=True)
# A WHOLE BUNCH OF FIELDS
# generate natural key
def natural_key(self):
return (self.voyage_id)
class Meta:
ordering = ['voyage_id',]
verbose_name = 'Voyage'
verbose_name_plural = "Voyages"
def __unicode__(self):
return "Voyage #%s" % str(self.voyage_id)
子模型:
class Image(models.Model):
voyage = models.ForeignKey(Voyage, null=True, blank=True)
# MANY OTHER FIELDS
class Meta:
verbose_name = "Image"
verbose_name_plural = "Images"
ordering = ["date"]
治具:
{
"pk": 340,
"model": "resources.image",
"fields": {
"category": 56,
"voyage": 41890,
"date": 1873,
"description": "blah blah blah",
"language": " ",
"creator": null,
"title": "Catherine Zimmermann-Mulgrave, \nc.1873",
"source": "blah blah blah",
"ready_to_go": true,
"file": "images/5AF81DA065049ACE0EC8E236C445F5BC.JPG",
"order_num": 0
}
}
最佳答案
所以这就是我最终想出的
该函数期望输入来自元组:
def get_by_natural_key(self, voyage_id):
return self.get(voyage_id=voyage_id)
当指定 --natural 标志时,此函数生成元组
def natural_key(self):
return (self.voyage_id)
这里的窍门是,当您有一个只有一个元素的元组时,它会恢复为原始类型(str,int等),以强制单个元素元组,您需要在结尾加上“,”,因此解决方法是:
def natural_key(self):
return (self.voyage_id,)
关于python - 具有自然键的Django loaddata无法查询正确的外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21151544/