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"
},
我在将字段名更改为model name之后解决了这个问题。在
相关问题 更多 >
编程相关推荐