2👍
✅
You can ues drf-nested-routers
(https://github.com/alanjds/drf-nested-routers).
The only interesting part in the code below is setting the track playlist in the pre_save
method of the TrackViewSet
.
views.py
class TrackViewSet(viewsets.ModelViewSet):
queryset = Track.objects.all()
serializer_class = TrackSerializer
def pre_save(self, obj):
obj.playlist = Playlist.objects.get(pk=self.kwargs['playlist_pk'])
class PlaylistViewSet(viewsets.ModelViewSet):
queryset = Playlist.objects.all()
serializer_class = PlaylistSerializer
def pre_save(self, obj):
obj.user = self.request.user
urls.py
from django.conf.urls import patterns, url, include
from rest_framework_nested import routers
from . import views
router = routers.SimpleRouter()
router.register(r'playlists', views.PlaylistViewSet)
playlists_router = routers.NestedSimpleRouter(router, r'playlists', lookup='playlist')
playlists_router.register(r'tracks', views.TrackViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^', include(playlists_router.urls)),
)
Source:stackexchange.com