DRF序列化器通过请求用户获取喜欢的数据

时间:2017-02-17 10:36:14

标签: django django-rest-framework

我正在制作像facebook这样的社交应用。 当得到帖子(在新闻提要)数据时,如果我按下该帖子,我想得到布尔值。

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Post(models.Model):
    uploader = models.ForeignKey(User)
    likes = models.IntegerField(default=0)
    point = models.IntegerField(default=0)
    isPointReceived = models.BooleanField(default=False)

    content = models.TextField()
    uploadedTime = models.DateTimeField(auto_now=True)
    # editedTime = models.DateTimeField()
    def __str__(self):
        return ("[uploader = " + self.uploader.username + "]") + (", [id = " + (str)(self.id) + "]") + ("[content = " + self.content[:50] + "]")


class PostLike(models.Model):
    post = models.ForeignKey(Post, related_name='postLikes')
    liker = models.ForeignKey(User)
    def __str__(self):
        return "Like" + "| [Post = " + (str)(self.post) + "]" + ", [Liker = " + self.liker.username + "]"

serializers.py

class PostLikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostLike
        fields = '__all__'


class PostListSerializer(serializers.ModelSerializer):
    uploader = UserDetailSerializer()
    isMine = serializers.SerializerMethodField()
    isLiked = serializers.SerializerMethodField()
    postComments = PostCommentSerializer(many=True, allow_null=True)
    class Meta:
        model = Post
        fields = ('uploader', 'id',  'likes', 'point', 'isPointReceived', 'content', 'uploadedTime', 'postComments', 'isMine', 'isLiked',)


    def get_isMine(self, obj):
        requestUser = CurrentUserDefault()
        return obj.objects.fileter(uploader=requestUser).exists()
        # return obj.filter(uploader=requestUser)


    def get_isLiked(self, obj):
        requestUser = CurrentUserDefault()
        return PostLike.objects.filter(post=obj, liker=requestUser).exists()
        #
        # try:
        #     PostLike.objects.get(post=obj, liker=requestUser)
        #     return True
        # except:
        #     return False

我尝试了很多脏东西。但是没有解决方案......

结论: 如果用户有PostLike(post=post, user=user)

的记录,则使用HTF获取数据
  • 如何让用户进入序列化程序类。

或者我应该以不同的方式处理这个问题? 比如管理APIView中的喜欢数据等等...

帮助!

====== EDITED ========== 最终代码应如下所示。 在serialziers.py中

class PostListSerializer(serializers.ModelSerializer):
    uploader = UserDetailSerializer()
    postComments = PostCommentSerializer(many=True, allow_null=True)
    postLikes = PostLikeSerializer(many=True, allow_null=True)
    postImages = PostImageSerializer(many=True, allow_null=True)
    isMine = serializers.SerializerMethodField()
    isLiked = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('uploader', 'id',  'likes', 'content', 'uploadedTime', 'postComments', 'postLikes', 'postImages', 'isMine', 'isLiked',)


    def get_isMine(self, obj):
        requestUser = self.context['request'].user
        return obj.uploader == requestUser


    def get_isLiked(self, obj):
        requestUser = self.context['request'].user
        return PostLike.objects.filter(post=obj, liker=requestUser).exists()

2 个答案:

答案 0 :(得分:2)

您可以从序列化程序方法中的序列化程序上下文中获取用户:

self.context['request'].user

它是从最初在get_serializer_context

中创建的方法GenericAPIView传递的
class GenericAPIView(APIView):
    ....
    def get_serializer_context(self):
        """
        Extra context provided to the serializer class.
        """
        return {
            'request': self.request,
            'format': self.format_kwarg,
            'view': self
        }

如您所见,您也可以从上下文中获取formatview。您也可以覆盖此方法以设置其他上下文。

答案 1 :(得分:0)

def get_isLiked(self, obj):
    requestUser = self.context['request'].user
    return PostLike.objects.filter(post=obj, liker=requestUser).exists()

如果结果有12个对象,它将执行12个类似的查询,这增加了您的响应时间。我正在寻找解决方案,以便可以通过一个查询来解决。不知道该怎么办。