如何使用Django REST Framework从多个模型中获得结果

时间:2014-03-12 07:13:11

标签: python django django-rest-framework

我有一些模特:用户/喜欢/不喜欢......

class Like(models.Model):
""" Like """
    user = models.ForeignKey(User)
    movie_id = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)

class Dislike(models.Model):
""" Dislike """
    user = models.ForeignKey(User)
    movie_id = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)

如何通过movie_id列表和当前用户使用Django REST Framework获得这样的结果?

movie_id = [11111,22222,33333,44444]

{
"results": [
    {
        "movie_id": 125405, 
        "like": True, 
        "dislike": False,
    }, 
    ...
    ]
}

LikeSerializer:

class LikeSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)

    class Meta:
        model = Like
        fields = ('id', 'user', 'movie_id', 'created')


class LikeViewSet(viewsets.ModelViewSet):
    model = Like
    serializer_class = LikeSerializer
    permission_classes = (IsAuthenticated,)

DisLikeSerializer:

class DislikeSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)

    class Meta:
        model = Dislike
        fields = ('id', 'user', 'movie_id', 'created')


class DislikeViewSet(viewsets.ModelViewSet):
    model = Dislike
    serializer_class = DislikeSerializer
    permission_classes = (IsAuthenticated,)

...谢谢

1 个答案:

答案 0 :(得分:1)

您可以向回复添加自定义字段。

我们无法使用like。作为python中的保留关键字。看到这段代码。实现同样的不喜欢。

class LikeSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)
    likes = serializers.SerializerMethodField('no_likes_get')

    def no_likes_get(self, like_obj):
        return Like.objects.filter(movie_id = like_obj.movie_id).count()

    class Meta:
        model = Like
        fields = ('id', 'user', 'movie_id', 'likes')