在Django中序列化的一对一关系

时间:2018-05-24 20:32:59

标签: python django django-rest-framework django-serializer

我有以下User

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    username = models.CharField(null=False, unique=True, max_length=255)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

以下UserProfile模型,

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, )
    level = models.CharField(default="Noob", max_length=255)
    reputation = models.IntegerField(default=0)
    status = models.CharField(max_length=255, null=True, blank=True)

用户与Profile具有一对一的关系。 这是UserSerializer

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    location = LocationSerializer(read_only=True)
    profile = UserProfileSerializer(read_only=True)

    class Meta:
        model = models.User
        fields = (
            'id', 'email', 'mobile', 'username', 'full_name', 'password', 'is_active', 'profile',

        )

这是配置文件序列化程序。

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserProfile
        fields = ('level', 'reputation', 'status',)

问题是在用户的序列化输出中没有嵌套的配置文件数据。我该如何解决。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:4)

profile

设置source所需的一切
class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    location = LocationSerializer(read_only=True)
    profile = UserProfileSerializer(source='userprofile', read_only=True)

userprofile是您的模型User与onetoone与UserProfle的关系名称,您可以为related_name设置属性user的其他方式 UserProfle

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)

然后您的序列化工具将正常工作。