在我的应用程序中,用户有一面墙,类似于以前的Facebook墙。用户可以在其他用户的墙上发表评论。我有一个基本结构如下的序列化程序:
class UserWallCommentSerializer(serializers.ModelSerializer):
class Meta:
model = UserWallComment
fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
read_only_fields = ('uid', 'uidcommenter', 'idwall', 'created')
uid
和uidcommenter
是用户模型的外键,idwall
是PK,description
是注释本身。在
创建/编辑注释时,uid
和{
假设我的视图中有变量uid
和uidcommenter
正在调用序列化程序-如何将这些变量传递给序列化程序,以便创建UserWallComment?在
我尝试过使用SerializerMethodField
(在上下文变量中传递PK)来设置uid
和{
我的视图代码(idwall
是墙的pk):
class MemberWall(APIView):
def post(self, request, requestUid, idwall):
uid = request.user.uid
serializer = UserWallCommentSerializer(data=request.DATA, context={'uid': requestUid, 'uidcommenter': uid})
if serializer.is_valid():
serializer.save()
return Response(serializer.data['uid'], status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
文档中说
SerializerMethodField
只用于representation of the object。这意味着只有当您将数据作为响应返回时才使用它。在默认情况下,序列化程序获取传递的请求:
这意味着您可以覆盖de default save,更新serializer的方法并设置相关字段。您应该可以使用:
self._context.request.user.uid
我没试过,但应该行得通。在
相关问题 更多 >
编程相关推荐