gpt4 book ai didi

python - Django REST Framework - 序列化外键字段

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:16 24 4
gpt4 key购买 nike

在我的应用程序中,用户有一堵墙,类似于旧的 Facebook 墙。用户可以在其他用户墙上发表评论。我有一个具有如下基本结构的序列化器:

class UserWallCommentSerializer(serializers.ModelSerializer):
class Meta:
model = UserWallComment
fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
read_only_fields = ('uid', 'uidcommenter', 'idwall', 'created')

uiduidcommenter 是用户模型的外键,idwall 是 PK,description 是用户模型的外键。评论本身。

创建/编辑评论时,后端需要设置uiduidcommenter。不允许用户更改这些字段。

假设我有变量 uiduidcommenter 在我看来正在调用序列化器 - 如何将这些变量传递给序列化器,以便 UserWallComment 是创建了吗?

我尝试使用 SerializerMethodField 设置 uiduidcommenter (在上下文变量中传递 PK),但数据库显示我是传递 NULL PK:

class UserWallCommentSerializer(serializers.ModelSerializer):
uid = serializers.SerializerMethodField('setUid')
class Meta:
model = UserWallComment
fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
read_only_fields = ('uidcommenter', 'idwall', 'created')
def setUid(self):
return self.context['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 。这意味着仅当您返回数据作为响应时才会使用它。

默认情况下,序列化器获取传递的请求:

def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}

这意味着您可以覆盖serializer的默认保存、更新方法。并设置相关字段。您应该能够使用以下方式访问:self._context.request.user.uid

我没有尝试过,但它应该有效。

关于python - Django REST Framework - 序列化外键字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21534239/

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