首页 > 解决方案 > 如何使用 django-import-export 获取嵌套的 json 导出?

问题描述

我正在使用 django-import-export,我想导出到嵌套关系的 json。因此,假设我使用文档(书籍/作者/类别)中的示例,并且我想导出所有书籍,包括它的作者和类别。我希望导出包含作者和类别作为对象,这样它看起来像这样:

[
    {
        "name": "Hitchhikers guide to the galaxy",
        "Author": {"name": "Douglas Adams"}
        "categories": [{"name": "Science fiction"}, {"name": "classics"}]
        "imported": true
    },
    {
        "name": "Don Quixote",
        "Author": {"name": "Miguel de Cervantes"},
        "categories": [{"name": "Idiots"}]
        "imported": true
    }
]

我正在查看文档,但找不到如何实现这一点。有人可以给我一个关于如何实现这一目标的提示吗?

[编辑]

我尝试这样做的原因是我们有一些模型包含我们在验收中测试的特定设置。一旦他们准备好了,我希望能够从验收中导出,然后将其导入生产。同样,我也希望能够从生产中导出并在接受中导入。

标签: pythonjsondjangodjango-admindjango-import-export

解决方案


在 django-import-export 中没有一种简单的方法可以做到这一点,但可以使用dehydrate()方法生成嵌套数据结构。

例如,在示例应用程序中,可以生成嵌套的 Author 字段,如下所示:

class BookResource(ModelResource):

    class Meta:
        model = Book

    def dehydrate_author(self, book):
        author = getattr(book, "author", None)
        if author:
            return {"name": author.name}
        return dict()

这将产生如下数据结构:

[{"id": 101, "name": "Fly Fishing", "author": {"name": "J. R. Hartley"}}]

推荐阅读