我想向序列化程序添加一个字段,该字段包含特定于发出当前请求的用户的信息(我不想为此创建单独的端点)。我是这样做的:
视图集:

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    filter_class = ArticleFilterSet

    def prefetch_likes(self, ids):
        self.current_user_likes = dict([(like.article_id, like.pk) for like in Like.objects.filter(user=self.request.user, article_id__in=ids)])

    def get_object(self, queryset=None):
        article = super(ArticleViewSet, self).get_object(queryset)
        self.prefetch_likes([article.pk])
        return article

    def paginate_queryset(self, queryset, page_size=None):
        page = super(ArticleViewSet, self).paginate_queryset(queryset, page_size)
        if page is None:
            return None

        ids = [article.pk for article in page.object_list]
        self.prefetch_likes(ids)

        return page

序列化程序:
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article

    def to_native(self, obj):
        ret = super(ArticleSerializer, self).to_native(obj)

        if obj:
            view = self.context['view']
            ret['has_liked'] = False
            if hasattr(view, 'current_user_liked'):
                ret['has_liked'] = obj.pk in view.current_user_liked

        return ret

有没有更好的地方注入喜欢的文章,或一个更好的方法来做这一般?

最佳答案

您可以使用SerializerMethodField
例子:

class PostSerializer(serializers.ModelSerializer):
    fav = serializers.SerializerMethodField('likedByUser')

    def likedByUser(self, obj):
        request = self.context.get('request', None)
        if request is not None:
            try:
                liked=Favorite.objects.filter(user=request.user, post=obj.id).count()
                return liked == 1
            except Favorite.DoesNotExist:
                return False
        return "error"

    class Meta:
        model = Post

然后您应该从如下视图调用序列化程序:
class PostView(APIVIEW):
     def get(self,request):
         serializers = PostSerializer(PostObjects,context={'request':request})

关于python - 将用户特定字段添加到Django REST Framework序列化程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19468478/

10-10 08:28