【问题标题】:Django Nested Serializer - Return Null Field if condition is fullfiledDjango Nested Serializer - 如果满足条件,则返回 Null 字段
【发布时间】:2021-10-24 18:16:09
【问题描述】:

我有一个嵌套的序列化,如果父序列化器字段“is_profile_private”(布尔值)为 True,我需要将其返回为 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",
        )

views.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))

【问题讨论】:

    标签: python django api serialization django-rest-framework


    【解决方案1】:

    你可以使用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
    

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

    【讨论】:

    • UserProfileSerializer(obj.user).data obj.user 是我在尝试 SerializerMethodField 时错过的东西。谢谢
    猜你喜欢
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多