這是我的問題。我正在嘗試加載一些與另一個模型具有自然關係的數據。Django loaddata與自然鍵不查詢正確的外鍵
我修改了父模型來生成自然鍵。
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而不是voyage_voyage.voyag e_id在get_by_natural_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
}
}
** voyage.voyage **模型已經加載。對於此特定對象,41890位於voyage_id字段中,而不是voyag.id字段。我認爲自然鍵的全部概念是,對於現有數據,pk可以是(通常不是靜態值),因此可以使用另一個字段來標識將子記錄與父項關聯的記錄。 – Alex