DRF - 如何将序列化模型与自定义字段连接起来

DRF - How to concatanate serialized model with custom field

我需要使用自定义字段连接序列化模型 = list[]

我有一个 user_profile 模型,我想知道特定用户是否是“我的(活跃用户的)”朋友,在用户列表中(list_boolean = ["True", "False ", "正确"])

views.py

class User_profile_view(APIView):
    def get(self, request): 

        #this is example list which i need to link
        list_boolean = ["True", "False", "True"]
        query = User_profile.objects.all()
        serializer_class = User_profile_serializer(query, many=True)
        return Response(serializer_class.data)

models.py

class User_profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    age = models.CharField(max_length=100)
    city = models.CharField(max_length=100)

serializer.py

class User_profile_serializer(serializers.ModelSerializer):
    class Meta:
        model = User_profile
        exclude = ["id"]

这里有什么方法可以 link 特定列表,对象吗?它可能在对象内部(哪个更好)或外部

您可以使用 SerializerMethodField 添加此信息。

class User_profile_serializer(serializers.ModelSerializer):
    class Meta:
        model = User_profile
        exclude = ["id"]    
    is_friend = serializers.SerializerMethodField()

    def get_is_friend(self, ob):
        #some query to determine if the user in question (ob) is a friend with the current user (self.context['current_user'])
        return True/False