python - 在 Django 中序列化一对一关系

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

我有以下用户

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)

User 与 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',)

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

最佳答案

您只需要设置 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 的关系名称,由一个到 UserProfle,您可以通过其他方式设置 related_name 中的属性 user 用户配置文件

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

那么您的序列化器将按原样正常工作。

关于python - 在 Django 中序列化一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50517745/

相关文章:

python - 如何将我自己的错误附加到 Django 表单的 ErrorDict 中?

python - 在单个方法上启用 django 的 TEMPLATE_STRING_IF_INVALID

django - 自动生成的字段 'user_ptr' 与声明的同名字段冲突

python - 使用 Python 启动 VirtualBox 虚拟机

Python 脚本卡在循环中

python - Argparse 表示时间段,以小时或天为单位

django-rest-framework - 为什么 `pk=None` 在 `detail_route` 的 DRF 文档中?它是否必须默认为无?

python - 使用多索引列展平 DataFrame

mysql - 最好为每个具有选项的单独列创建表格,或者在 django 的模型类中创建选项元组

Django Rest Framework 使用 PrimaryKeyRelatedField 返回嵌套对象