python - 如何使用 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
}
]
我正在查看文档,但找不到如何实现这一点。有人可以给我一个关于如何实现这一目标的提示吗?
[编辑]
我尝试这样做的原因是我们有一些模型包含我们在验收中测试的特定设置。一旦他们准备好了,我希望能够从验收中导出,然后将其导入生产。同样,我也希望能够从生产中导出并在接受中导入。
解决方案
在 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"}}]
推荐阅读
- python - TypeError:在列表上应用自制伯努利拟合时无法使用灵活类型执行减少
- ms-access - 有没有办法在 Access 的文本框中添加一行或下划线部分的文本?
- python - 特定于代码:加密消息,并使索引超出范围错误
- wordpress - WPengine 和 git
- c++ - 我的 C++ 函数似乎没有被调用
- python - 派生查询上的 Django 内部联接
- xamarin - Android 应用与为 x86 构建的 Android SDK 不兼容
- python - 表的一个字段,在 Django Tables 中为另一个字段所独有
- kdb - 列的条件更新
- ios - 如何使用 Swift 在 iOS 中以编程方式在显示和亮度中打开 NightShift