UserProfile模型已将OneToOneField连接到User模型。 我想显示嵌套字段中的详细信息。
我使用序列化器来表达嵌套关系。但是结果是一样的。
通过用户实例访问用户配置文件没有问题。 例如
user = User.objects.get(username="test")
user.userprofile.super_user = True
有人可以帮我吗?
* models.py *
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
phone_no = models.CharField(max_length=10, null=True)
super_user = models.BooleanField(default=False)
admin_user = models.BooleanField(default=False)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
* serializers.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"
},
但结果不会显示如下所示的“个人资料”字段。
"user": {
"id": 1,
"username": "testUser",
"first_name": "",
"last_name": "",
"email": "",
"organization": "testOrg"
},
答案 0 :(得分:1)
我更改了与模型名称相同的字段名称后解决了这个问题。
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",
)