2014-03-12 83 views
0

我有幾種模式:用戶/喜歡/不喜歡......我怎樣才能從多個模型的結果與Django的REST框架

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) 

我怎樣才能得到這樣Django的REST框架結果進行movie_id列表當前用戶?

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

謝謝...

+0

顯示'LikeViewSet'和'DislikeViewSet'類的代碼。 –

+0

補充,thks .... – Flowerowl

+0

添加答案。嘗試一下 。讓我知道。工作與否。未經測試。 –

回答

0

你可以添加自定義字段到響應。我們不能使用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') 
+0

thks爲您的答案,我已經改變了我的模型,狀態:喜歡/不喜歡/等。 – Flowerowl

+0

我從來沒有使用過SerializerMethodField,這次我試試它,太棒了! – Flowerowl