Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested URL Patterns in Django REST Framework

I'm trying to go beyond Django REST Frameworks initial flat URL patterns. For example, if I have object types parentobject and childobject where parentobject HAS childobject(s) then the out of the box REST is as follows.

^ ^api/ ^ ^parentobject/$ [name='parentobject-list']
^ ^api/ ^ ^parentobject/\.(?P<format>[a-z]+)$ [name='parentobject-list']
^ ^api/ ^ ^parentobject/(?P<pk>[^/]+)/$ [name='parentobject-detail']
^ ^api/ ^ ^parentobject/(?P<pk>[^/]+)/\.(?P<format>[a-z]+)$ [name='parentobject-detail']
^ ^api/ ^ ^childobject/$ [name='childobject-list']
^ ^api/ ^ ^childobject/\.(?P<format>[a-z]+)$ [name='childobject-list']
^ ^api/ ^ ^childobject/(?P<pk>[^/]+)/$ [name='childobject-detail']
^ ^api/ ^ ^childobject/(?P<pk>[^/]+)/\.(?P<format>[a-z]+)$ [name='childobject-detail']

Within the parentobject responses, there will be references to the childobject(s) id.

GET /api/parentobject/1/

(results in)
{
    "childobject": [123, 456, 789]
}

If you want details on the childobject (or all the childobjects in the db) you can reference the childobject api.

/api/childobject/
/api/childobject/123/

On the same page still? :)

What I want to do is to create a generic/extensible way of referring to child m2m relationships through the parentobject api without having to pull ids, and then requery the childobject api.

/api/parentobject/1/childobject/

[
    {
        "childobject_prop": 1
        ...etc
    }
]

So the above would be childobject(s) filtered based on the parentobject reference in the m2m through table managed by Django.

The idea being also that this would be generic to the extent that I could define a new through relationship and have this capability with minimal work. e.g. the url patterns would be automatically, etc.

Additionally, any descending relationships would be handled in the same way. Such that "someotherchildobject" below would return the list of someotherchildobject(s) that are mapped to childobject '123', that are mapped to parentobject '1'.

/api/parentobject/1/childobject/123/someotherchildobject/

If that isn't clear enough then let me know. My success thus far has been limited. I don't want to modify Django REST to accomplish this, and at the same time I don't want to contruct URL patterns 'manually' by adding the specific ones I'm interested in into the urlpatterns.

Also, as a bonus, I want this to apply to CUSTOM through= tables in Django; and map any additional fields on the through table onto fields in the returned data similar to this.

Thanks!

like image 298
chris.guethle Avatar asked Jun 20 '13 14:06

chris.guethle


1 Answers

You should investigate https://github.com/alanjds/drf-nested-routers/

This has been suggested in https://github.com/tomchristie/django-rest-framework/pull/1048

like image 138
Thomas Grainger Avatar answered Oct 03 '22 03:10

Thomas Grainger