Django REST框架demo app公开了两个集合,/users/和/snippets/。
在我的应用程序中,我希望能够嵌套这些集合,例如要为用户5加载代码段,我请求/users/5/snippets/
这种配置在Django REST Framework中是否可行?我该如何设置呢?
答案 0 :(得分:8)
url(r'^/sessions/(?P<session_pk>\d+)/speakers/$', views.SpeakerBySessionList.as_view()),
class SpeakerBySessionList(generics.ListCreateAPIView):
model = Speaker
serializer_class = serializers.SpeakerSerializer
def get_queryset(self):
session_pk = self.kwargs.get('session_pk', None)
if session_pk is not None:
return Speaker.objects.filter(session__pk=session_pk)
return []
class Session(models.Model):
name = models.CharField(max_length=150)
class Speaker(models.Model):
name = models.CharField(max_length=100)
session = models.ForeignKey(Session, related_name='speakers')
如果你想看一个更复杂的django / ember示例,请务必查看我的github项目