我有这样的序列化器
class PublicacionSerializer(serializers.ModelSerializer):
usuario = UserSerializer2()
likeado = serializers.SerializerMethodField()
class Meta:
model = Publicacion
fields = ('id','usuario', 'likeado')
def get_likeado(self, obj):
user = self.context['request'].user
try:
like = Like.objects.get(publicacion=obj, usuario=user)
return like.id
except Like.DoesNotExist:
return False
所以我在另一个中使用了该序列化器:
class EstadoSerializer(serializers.ModelSerializer):
publicacion = PublicacionSerializer(read_only=True)
在views.py中我有
class ModificarEstadoMixin(object):
queryset = Estado.objects.all()
serializer_class = EstadoSerializer
class ModificarEstadoDetail(ModificarEstadoMixin, RetrieveUpdateAPIView):
permission_classes = (permissions.IsAuthenticated,
CanModifEstado,)
pass
当我访问网址以了解用户是否喜欢某个帖子时,我收到了KeyError'请求'在代码行
user = self.context['request'].user
有谁知道如何解决它?
答案 0 :(得分:4)
当您调用该序列化程序时,您必须从视图中传递上下文,如
MySerializer(context={'request': request})