如何从没有 'attrs' 参数的方法访问序列化器属性

How to access a serializer attribute from a method with no 'attrs' argument

我试图从我的 'get_other_user' 方法中访问我的对话序列化程序中的参与者属性。 我的参与者属性 returns 用户词典列表。

但是,当我 运行 时,我得到的模型代码没有属性 'participants'。我假设我必须将一个 'attrs' 参数传递给 'get_other_user' 方法(类似于 'def validate(self, attrs) 方法),然后使用 attrs.get('参加者)。但是在我的get_other_username方法中调用这个方法的时候不知道attrs参数怎么填写

如有任何建议,我们将不胜感激。 谢谢!

class ConversationSerializer(serializers.ModelSerializer): 

    other_username = serializers.SerializerMethodField(method_name='get_other_username', read_only=True)
    other_user_email = serializers.SerializerMethodField(method_name='get_other_user_email', read_only=True)
    # latest_message = serializers.SerializerMethodField(method_name='get_latest_message', read_only=True)
    participants = UsersSerializer(many=True, read_only=True)



    class Meta:
        model = Conversation
        fields = ['conversation_id' ,'participants','other_username', 'other_user_email']

    def get_current_user_id(self):
        user_id = self.context['current_user'].id
        return user_id

     
    def get_other_user(self):
        current_user_id = self.get_current_user_id()
        for participant in self.participants:
            if participant['id'] != current_user_id:
                return participant




    def get_other_username(self, obj):
        other_user = self.get_other_user()
        return other_user['username']

    def get_other_user_email(self, obj):
        other_user = self.get_other_user()
        return other_user.email        

您可以将对象作为参数传递给方法字段函数,并对其进行迭代。我通常只使用 get_{FIELD_NAME} 模式来使用带有填充它的函数的方法字段。

class ConversationSerializer(serializers.ModelSerializer):
    other_username = serializers.SerializerMethodField(read_only=True)
    participants = UsersSerializer(many=True, read_only=True)

    class Meta:
        model = Conversation
        fields = [
            "participants",
            "other_username",
        ]

    def get_current_user_id(self):
        user_id = self.context["current_user"].id
        return user_id

    def get_other_username(self, obj):
        current_user_id = self.get_current_user_id()
        for participant in obj.participants.all():
            if participant.id != current_user_id:
                return participant

这将 return 不是请求用户的第一个用户,如果您可以在超过 2 个人之间进行对话,您可能需要做一些修补。