简体   繁体   中英

How to get nested json export using django-import-export?

I'm using django-import-export and I want to do exports to json in which relations are nested. So let's say I use the example from the docs (Book/Author/Category) and I want to do an export of all books, including it's authors and categories. I would expect the export to include the authors and categories as objects so that it looks something like this:

[
    {
        "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
    }
]

I'm looking through the documentation but I can't find how I could achieve that. Could anybody give me a tip on how to achieve that?

[EDIT]

The reason I'm trying to do this is that we have some models containing specific settings which we test in Acceptance. Once they are good to go I want to be able to do an export from acceptance, and then import that into production. Likewise, I also want to be able to export from production and import in acceptance.

There is not a simple way of doing this in django-import-export but it is possible to generate nested data structures using dehydrate() methods.

For example, in the example application one can produce a nested Author field as follows:

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()

This will result in a data structure like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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