torchbox / wagtailapi

A module for adding a read only, JSON based web API to your Wagtail site (NO LONGER MAINTAINED! Use Wagtails contrib.wagtailapi module instead)
6 stars 4 forks source link

Example of setting up nested resources #4

Open mmmoli opened 9 years ago

mmmoli commented 9 years ago

I'm trying to get a nested resource into the api output. But I'm only seeing the foreign key.

I've got a structure like so:

class BlogCategory(models.Model):
    name = models.CharField(max_length=20)

    api_fields = ('name',)

class BlogPost(Page):
   ...
   category = models.ForeignKey('BlogCategory',
        on_delete=models.PROTECT,
        related_name="categories")

    api_fields = ('title', 'category',)

This results in an API response like:

{
    id: 4,
    meta: {
        type: "blog.BlogPost",
        parent: 2
    },
    title: "Is there more to wireframing than boxes and arrows?",
    category: 3
}

I'm looking for something more like:

{
    id: 4,
    meta: {
        type: "blog.BlogPost",
        parent: 2
    },
    title: "Is there more to wireframing than boxes and arrows?",
    category: {
        name: "UX & Glossary"
    }
}

Any tips? Only see a mention of relatedLink in the tests.

Thanks

Ace addition to Wagtail btw.

kaedroho commented 9 years ago

We've merged this module into Wagtail 1.0 (you can find it in the 1.0rc1 release) and have made a few changes to the way foreign keys are serialised:

    ...

    category: {
        id: 3,
        meta: {
            "type": "blog.Category",
            "detail_url": "http://api.example.com/categories/3/"
        }
    }

Out of the box, this doesn't allow you to stick the name field into that nested mapping. This is a feature that we hope to have implemented in Wagtail API soon.

Ibrokola commented 7 years ago

Just wondering if ability to nest categories has been implemented yet?

kaedroho commented 7 years ago

Yes, It's implemented in Wagtail API v2. See http://docs.wagtail.io/en/v1.13/advanced_topics/api/v2/usage.html#additional-fields

With the above configuration, you should be able to get the category name nested by adding ?fields=category(name) to the URL.