如何实现嵌套模型/路由? [英] How to implement nested models/routes?
问题描述
我有一个播放列表模型和一个跟踪模型。
I have a Playlist Model and a Track model.
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),允许我在播放列表/< playlist_id>
中列出播放列表的曲目,并创建相同网址的曲目。
How would I go about creating views (using viewsets preferably) that allow me list a playlist's tracks at playlists/<playlist_id>
and also create tracks at the same url?
I当我去上面的网址时,目前得到 non_field_errors
。
I currently get non_field_errors
when I go to the above url.
找不到很多关于如何做这些嵌套文件上的意见。谢谢。
Couldn't find much on how to do these nested views on the docs. Thanks.
推荐答案
您可以使用 drf-nested-router
(< a href =https://github.com/alanjds/drf-nested-routers =nofollow> https://github.com/alanjds/drf-nested-routers )。
下面代码中唯一有趣的部分是在的
。 pre_save
方法中设置曲目播放列表, TrackViewSet
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)),
)
这篇关于如何实现嵌套模型/路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!