Django loaddata与自然键不查询正确的外键

时间:2014-01-16 01:04:38

标签: python django django-fixtures

这是我的问题。我正在尝试加载一些与另一个模型具有自然关键关系的数据。

我修改了父模型以生成自然键。

我使用以下命令从旧数据库导出数据:

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。我仔细检查了,夹具中的钥匙在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
    }
}

2 个答案:

答案 0 :(得分:8)

所以这就是我最终想到的

此函数希望输入来自元组:

def get_by_natural_key(self, voyage_id):
        return self.get(voyage_id=voyage_id)

当指定 - 自然标志时,此函数会生成元组

def natural_key(self):
        return (self.voyage_id)

这里的技巧是,当你有一个只有一个元素的元组时,它会恢复到原来的类型(str,int等)来强制单个元素元组,你需要一个尾随“,”所以修复是:< / p>

def natural_key(self):
        return (self.voyage_id,)

答案 1 :(得分:0)

问题是

{
    "pk": 41890, 
    "model": "voyage.voyage", 
    "fields": {
        ...
    }
}

在images.json文件中,如果没有,我猜你必须以某种方式将它包含在转储中