简体   繁体   English

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

[英]How to work with ManytoManyField with through relation in django-rest-framework

Basically I have models like this: 基本上我有这样的模型:

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)

Now I want an API to return PLAYLISTS like this... But Videos should be sorted by POSITION in PlaylistVideo Model 现在我想要一个API来返回这样的PLAYLISTS ...但是视频应该按PlaylistVideo模型中的POSITION排序

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

How should I got about it? 我该怎么办呢?

Not too sure if you've managed to solve your issue, but I've came across this myself, and managed to make it work like by doing something like this: 不太确定你是否已经设法解决了你的问题,但我自己也遇到过这个问题,并设法让它像这样做:

create a custom serializer like this: 创建一个这样的自定义序列化器:

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

Here, I'm assuming you'd like to display all the fields under videos entity/table. 在这里,我假设你想显示视频实体/表格下的所有字段。 Feel free to adjust to your needs/likings. 随意调整您的需求/喜好。

Then, all you need to do is this 然后,你需要做的就是这个

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

Note: Always make sure that the source is referencing to the associative entity. 注意:始终确保源引用关联实体。 Else you'd get a list of empty json. 否则你会得到一个空的json列表。

Hope this would help anyone out there facing similar issue. 希望这可以帮助那些面临类似问题的人。

You can do it like this: 你可以这样做:

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

in serializers.py: 在serializers.py中:

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

We need to add some documentation on 'through' relationships really. 我们需要真正添加一些关于“通过”关系的文档。

In the meantime, this discussion may help: 与此同时,这个讨论可能会有所帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM