如何实现嵌套模型/路由?

时间:2014-05-15 19:19:37

标签: django django-rest-framework

我有播放列表模型和曲目模型。

class Playlist(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, related_name="playlists")

class Track(models.Model):
    playlist = models.ForeignKey(Playlist, related_name="tracks")
    track_id = models.CharField(max_length=50)

序列化器:

class TrackSerializer(serializers.ModelSerializer): 
    class Meta:
        model = Track
        fields = ("id", "track_id")

class PlaylistSerializer(serializers.ModelSerializer):
    user = serializers.Field(source="user.username")
    tracks = TrackSerializer(many=True)
    class Meta:
        model = Playlist
        fields = ("id", "created", "user", "tracks")

我如何创建视图(最好使用视图集),允许我在playlists/<playlist_id>列出播放列表的曲目,并在同一个网址创建曲目?

当我转到上面的网址时,我目前得到non_field_errors

无法找到有关如何在文档上执行这些嵌套视图的更多信息。感谢。

1 个答案:

答案 0 :(得分:2)

您可以drf-nested-routershttps://github.com/alanjds/drf-nested-routers)。

以下代码中唯一有趣的部分是使用pre_save的{​​{1}}方法设置曲目播放列表。

views.py

TrackViewSet

urls.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