如何实现嵌套模型/路线?(How to implement nested models/routes

2019-10-20 03:44发布

我有一个播放列表模式和轨道模型。

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")

我将如何去创建视图(使用viewsets最好),允许我在列出播放的曲目playlists/<playlist_id>也可以创建在同一个URL的轨道?

我目前得到non_field_errors当我去到上述网址。

找不到太多关于如何做的文档这些嵌套的看法。 谢谢。

Answer 1:

您可以正餐drf-nested-routers ( https://github.com/alanjds/drf-nested-routers )。

在下面的代码唯一感兴趣的部分是设置在所述轨道的播放列表pre_save所述的方法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)),
)


文章来源: How to implement nested models/routes?