首页 > 解决方案 > Django Nested Serializer - 如果条件已满,则返回 Null 字段

问题描述

我有一个嵌套的序列化,如果父序列化器字段“is_profile_private”(布尔值)为真,我需要将其返回为 Null。我尝试使用 get_queryset 来过滤用户配置文件,但没有取得任何进展。尝试使用 SerializerMethordField() 和 get_profile() 但 Django 抱怨 UserProfileSerializer 类型的对象不允许被序列化。

序列化程序.py

class UserProfileSerializer(UserSerializer):
    height = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        fields = (
            "bio",
            "gender",
            "custom_gender",
            "non_binary_list",
            "birthdate",
            "avatar",
            "height",
            "hometown",
            "zodiac_sign",
            "language",
        )

    @staticmethod
    def get_height(obj):
        return {"value": obj.height, "unit": obj.height_unit}


class SimpleUserSerializer(UserSerializer):
    profile = UserProfileSerializer(source="user", required=False)

    class Meta:
        model = User
        fields = (
            "id",
            "name",
            "username",
            "is_profile_private",
            "date_joined",
            "profile",
        )

视图.py

class UserProfileAPIView(RetrieveModelMixin, UpdateModelMixin, GenericViewSet):
    lookup_field = "id"
    queryset = User.objects.all()
    serializer_class = SimpleUserSerializer
    http_method_names = ["get"]

    @staticmethod
    def get(request, *args, **kwargs):
        return User.objects.get(id=str(request.data))

标签: pythondjangoapiserializationdjango-rest-framework

解决方案


您可以使用SerializerMethodField

class SimpleUserSerializer(UserSerializer):
    profile = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            "id",
            "name",
            "username",
            "is_profile_private",
            "date_joined",
            "profile",
        )

    def get_profile(self, obj):
        if obj.is_profile_private:
            return None
        return UserProfileSerializer(obj.user).data

请注意,您应该返回序列化程序的数据,而不是序列化程序本身。


推荐阅读