如何通过Django的REST的架构关系与ManytoManyField工作,(How to wor

2019-08-04 16:57发布

基本上我有模型是这样的:

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模型位置进行排序

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

我应该如何得到呢?

Answer 1:

也不太清楚,如果你已经成功地解决您的问题,但我碰到这个来了自己,并设法使它像做这样的工作:

创建这样的自定义序列:

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

希望这将帮助那里的人面临着类似的问题。



Answer 2:

你可以像下面这样做:

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

在serializers.py:

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


Answer 3:

我们需要“到”关系上添加一些文档真的。

在此期间,这种讨论可以帮助:

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



文章来源: How to work with ManytoManyField with through relation in django-rest-framework