3

Django REST Framework演示应用程序公开了两个集合,/users//snippets/

在我的应用程序中,我希望能够嵌套这些集合,例如为用户 5 加载片段,我会请求/users/5/snippets/

在 Django REST Framework 中可以进行这种配置吗?我将如何进行设置?

4

1 回答 1

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 项目

https://github.com/toranb/complex-ember-data-example

于 2013-02-27T21:02:02.243 回答