结果中不显示UserProfile的OneToOneField

2024-05-08 18:59:33 发布

您现在位置:Python中文网/ 问答频道 /正文

UserProfile模型有一个连接到用户模型的toonefield。 我想显示嵌套字段的详细信息。在

我使用序列化程序来表示嵌套关系。但结果是一样的。在

通过用户实例访问userprofile没有问题。 例如

user = User.objects.get(username="test")
user.userprofile.super_user = True

有人能帮帮我吗?在

*模型.py*

^{pr2}$

*序列化程序.py*

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ("phone_no", "super_user", "admin_user")


class UserSerializer(serializers.ModelSerializer):
    profile = UserProfileSerializer(read_only=True)
    # SerializerMethodField is read-only
    organization = serializers.SerializerMethodField()

    def get_organization(self, obj):
        if obj.groups is not None:
            return obj.groups.all().first().name
        return None

    class Meta:
        model = User
        fields = (
            "id",
            "profile",
            "username",
            "first_name",
            "last_name",
            "email",
            "organization",
        )

我想得到如下json格式。在

   "user": {
        "id": 1,
        "profile": {
            "phone_no": "",
            "super_user": "",
            "admin_user"
        }
        "username": "testUser",
        "first_name": "",
        "last_name": "",
        "email": "",
        "organization": "testOrg"
    },

但结果不像下面那样显示“profile”字段。在

   "user": {
        "id": 1,
        "username": "testUser",
        "first_name": "",
        "last_name": "",
        "email": "",
        "organization": "testOrg"
    },

Tags: name模型idobjemailusernameprofileclass
1条回答
网友
1楼 · 发布于 2024-05-08 18:59:33

我在将字段名更改为model name之后解决了这个问题。在

class UserSerializer(serializers.ModelSerializer):
    userprofile = UserProfileSerializer(read_only=True)
    # SerializerMethodField is read-only
    organization = serializers.SerializerMethodField()

    def get_organization(self, obj):
        if obj.groups is not None:
            return obj.groups.all().first().name
        return None

    class Meta:
        model = User
        fields = (
            "id",
            "userprofile",
            "username",
            "first_name",
            "last_name",
            "email",
            "organization",
        )

相关问题 更多 >

    热门问题