python - 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))
解决方案
您可以使用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
请注意,您应该返回序列化程序的数据,而不是序列化程序本身。
推荐阅读
- c++ - 枚举类变量可以取整范围的整数值吗?
- reactjs - 在任何页面中重新加载时如何正确重新获取数据?
- python - xgettext 无法提取标签属性
- c# - 如何将 c# 应用程序连接到 ElasticMQ 容器?
- c# - 更新父实体时,EF Core 正在删除子实体
- postgresql - 如何在 PostgreSQL 中获取计数派生列的总和?
- oracle - ORA-08006: 指定的行不再存在
- mysql - 如何从 MySQL <= 5.7 中的数据库中提取和更新 MULTI JSON ARRAY?
- scala - 如何使用期货处理尾递归
- python - 如果变量上升错误中的空格如何打破 eval(variable)?