如何在django-rest-framework中通过关系使用ManytoManyField

时间:2012-12-25 17:46:10

标签: python django-rest-framework

基本上我有这样的模型:

class Playlist(models.Model):
    key = models.CharField(max_length=255,blank=True, unique=True)
    user = models.ForeignKey(User)
    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField(auto_now_add=True)
    videos = models.ManyToManyField(Video, through='PlaylistVideo')

class PlaylistVideo(models.Model):
    playlist = models.ForeignKey(Playlist)
    video =    models.ForeignKey(Video)
    position = models.IntegerField()

class Video(models.Model):
    title = models.CharField(max_length=255,blank=True)
    description = models.TextField(blank=True)
    thumb =  models.URLField(blank=True)
    duration = models.IntegerField(default=0)

现在我想要一个API来返回这样的PLAYLISTS ......但视频应按POSITION排序 播放列表视频模型

{
        "key": "h8x3",
        "title": "First Playlist",
        "pub_date": "2012-10-11T17:00:26Z",
        "videos": [
            {
                ....
            },
            {
                ....
            }
        ]
    },

我该怎么做?

3 个答案:

答案 0 :(得分:7)

不太确定你是否已经设法解决了你的问题,但我自己也遇到了这个问题,并设法让它像这样做:

创建一个这样的自定义序列化程序:

class PlaylistVideoSerializer(serializers.HyperlinkedModelSerializer):
    title = serializers.ReadOnlyField(video.title)
    description = serializers.ReadOnlyField(video.description)
    thumb = serializers.ReadOnlyField(video.thumb)
    duration = serializers.ReadOnlyField(video.duration)

    class Meta:
        # your associative entity here
        model = PlaylistVideo
        fields = ('title', 'description', 'thumb', 'duration')

在这里,我假设您要显示视频实体/表格下的所有字段。随意根据您的需求/喜好进行调整。

然后,你需要做的就是这个

class PlaylistSerializer(serializers.ModelSerializer):
    videos = PlaylistVideoSerializer(source='playlistvideo_set', many=True)
    class Meta: 
        model = Playlist
        fields = ('key', 'title', 'pub_dates', 'videos')

注意:始终确保源引用关联实体。否则你会得到一个空的json列表。

希望这可以帮助那些面临类似问题的人。

答案 1 :(得分:4)

你可以这样做:

class PlaylistVideoList(generics.ListCreateAPIView):
    serializer_class = PlaylistVideoSerializer
    queryset = PlaylistVideo.objects.all().order_by('position')

在serializers.py中:

class PlaylistVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlaylistVideo

答案 2 :(得分:1)

我们需要在“通过”关系中添加一些文档。

与此同时,这个讨论可能会有所帮助:

https://groups.google.com/forum/#!topic/django-rest-framework/xzOhjILq3xA/discussion