简体   繁体   English

使用自然键导入 django 夹具时出错

[英]Error when importing django fixture with natural key

In context of a django project, I want to create some sample data in forme of a fixture.在 django 项目的上下文中,我想以夹具的形式创建一些示例数据。 I have export my data with natural key to avoid any data overnight at the import but I'm not able to import data at all.我已经用自然键导出了我的数据,以避免在导入时一夜之间出现任何数据,但我根本无法导入数据。

The fixture has been created with the following command :夹具已使用以下命令创建:

python manage.py dumpdata --format yaml --natural-primary --natural-foreign conformity.policy conformity.measure  > conformity/fixture/NIST.yaml

I have tried to import the fixture with the following command :我尝试使用以下命令导入夹具:

python manage.py loaddata conformity/fixture/NIST.yaml

but I have the following error但我有以下错误

django.core.serializers.base.DeserializationError: Problem installing fixture 'conformity/fixture/NIST.yaml': ['“NIST Cybersecurity Framwork” value must be an integer.']: (conformity.measure:pk=None) field_value was 'NIST Cybersecurity Framwork' django.core.serializers.base.DeserializationError:安装夹具'conformity/fixture/NIST.yaml'时出现问题:['“NIST Cyber​​security Framwork”值必须是整数。']:(conformity.measure:pk=None)field_value是“NIST 网络安全框架”

It seems to me that django don't understand data correctly and try to use natural key directly as a primary key.在我看来,django 没有正确理解数据并尝试直接使用自然键作为主键。 I haven't found any option to change this behavior.我还没有找到任何改变这种行为的选择。

Of course YAML file don't have any pk for the object to be imported (du to natural key), I was expected Django to automatically generate them.当然,YAML 文件没有要导入的对象的任何 pk (du to natural key),我希望 Django 自动生成它们。

edit:编辑:

I have add the Manager class and the get_by_natural_key method recomanded by Abdul Aziz Barkat comment.我添加了由 Abdul Aziz Barkat 评论推荐的 Manager 类和 get_by_natural_key 方法。

class MeasureManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)


class Measure(models.Model):
[...]
    objects = MeasureManager()

    def natural_key(self):
        return (self.name,)
    natural_key.dependencies = ['conformity.policy']

but I still have the same issue.但我仍然有同样的问题。 Do you have any clue ?你有什么线索吗?

Two problem in one here, first, as pointed by Abdul Aziz Barkat , it keeded to implement the Manager class and the get_by_natural_key methode for my use case.这里有两个问题,首先,正如 Abdul Aziz Barkat 所指出的,它需要为我的用例实现 Manager 类和 get_by_natural_key 方法。 I havent hunderstand correctly the documentation on this point.我还没有正确理解关于这一点的文档。

second, the data exported by the dumpdata commande is not exactly the same, so I had to reimport an old version (with pk) re exported (without pk) and it work perfectly.其次, dumpdata命令导出的数据不完全相同,所以我不得不重新导入一个旧版本(带pk)重新导出(不带pk),它工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM