21

基本上我有这样的模型:

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 ......但是视频应该在 PlaylistVideo 模型中按 POSITION 排序

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

我该怎么办?

4

3 回答 3

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 的列表。

希望这会帮助任何面临类似问题的人。

于 2015-07-06T14:05:44.413 回答
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
于 2014-04-24T11:29:04.230 回答
2

我们确实需要添加一些关于“通过”关系的文档。

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

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

于 2012-12-29T14:19:49.767 回答