简体   繁体   English

Django REST Framework-序列化ForeignKey字段

[英]Django REST Framework - Serialize ForeignKey fields

In my app, users have a wall, similar to the old Facebook wall. 在我的应用中,用户有一堵墙,类似于旧的Facebook墙。 A user is able to post comments on other users walls. 用户可以在其他用户的墙上张贴评论。 I have a serializer with a base structure like this: 我有一个具有以下基本结构的序列化器:

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

uid and uidcommenter are foreignkeys to the user model, idwall is the PK, and description is the comment itself. uiduidcommenter是用户模型的外键, idwall是PK, description是注释本身。

When a comment is created/edited, uid and uidcommenter needs to be set by the backend. 创建/编辑注释时,后端需要设置uiduidcommenter A user can not be allowed to change these fields. 不允许用户更改这些字段。

Lets say I have the variables uid and uidcommenter in my view that is calling the serializer - how can I pass these variables along to the serializer so that a UserWallComment is created? 可以说我在调用序列化程序的视图中有变量uiduidcommenter如何将这些变量传递给序列化程序,以便创建UserWallComment?

I have tried setting uid and uidcommenter using the SerializerMethodField (passing the PK's in the context variable), but the database says I am passing NULL PK's: 我尝试使用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']

My view code ( idwall is the pk of the wall): 我的查看代码( 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)

the documentation says that the SerializerMethodField is used only for representation of the object . 该文档说SerializerMethodField仅用于对象的表示 Which means it is used only when you return your data as a response. 这意味着仅当您返回数据作为响应时才使用它。

By default the serializer get's the request passed: 默认情况下,序列化器获取传递的请求:

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

This means that you can overwrite de default save, update methods of the serializer and set the relevant fields. 这意味着您可以覆盖默认的保存,更新序列化程序的方法并设置相关字段。 You should be able to access then using: self._context.request.user.uid 然后,您应该可以使用: self._context.request.user.uid进行访问

I didn't try this but it should work. 我没有尝试过,但是应该可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM