簡體   English   中英

如何使用 django-import-export 獲取嵌套的 json 導出?

[英]How to get nested json export using django-import-export?

我正在使用 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"}}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM