【发布时间】: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