gpt4 book ai didi

django - DRF 序列化程序通过请求用户通过 post 获取喜欢的数据

转载 作者:行者123 更新时间:2023-12-01 01:53:38 24 4
gpt4 key购买 nike

我正在制作一个像 facebook 这样的社交应用程序。
当获取帖子(在新闻提要)数据时,如果我按下那个帖子,我想得到 bool 值。

模型.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 + "]"

序列化程序.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 或其他任何东西中管理喜欢的数据......

    帮助!

    ========编辑==========
    最终代码应如下所示。
    在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()

    最佳答案

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

    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从上下文。您还可以覆盖此方法以设置其他上下文。

    关于django - DRF 序列化程序通过请求用户通过 post 获取喜欢的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295692/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com