【问题标题】:One-to-One relationship not returning nested serializer in json response一对一关系未在 json 响应中返回嵌套序列化程序
【发布时间】:2019-08-30 01:17:56
【问题描述】:

我正在尝试在用户和个人资料模型之间实现一对一的关系,以便我可以使用一些嵌套的用户数据检索我的个人资料。

这是我的模型:

class User(AbstractUser):
    username_validator = CustomUnicodeUsernameValidator
    username = models.CharField(
        _('username'),
        max_length=20,
        unique=True,
        help_text=_('Required. 15 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    email = models.EmailField(
        _('email address'),
        unique=True,
        null=False,
        blank=False,
        error_messages={
            'unique': _("A user with that email already exists."),
        },
    )
    password = models.CharField(
        _('password'),
        max_length=128,
        null=False,
        blank=False,
    )

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        primary_key=True,
        parent_link=True,
        # related_name='usuario',
        # related_query_name='usuarios',
        on_delete=models.CASCADE
    )

    bio = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )

    birth_date = models.DateField(
        null=True,
        blank=True
    )

    avatar_url = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )

    cover_url = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )


def create_profile_post_save(sender, instance, created, **kwargs):
    if created:
        profile = Profile(user=instance)
        profile.save()


post_save.connect(create_profile_post_save, sender=settings.AUTH_USER_MODEL)

序列化器:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    full_name = serializers.CharField(
        source='get_full_name',
        read_only=True
    )

    password = serializers.CharField(
        min_length=8,
        required=True,
        allow_null=False,
        allow_blank=False,
        write_only=True,
        error_messages={
            'allow_null': 'Password cannot be null.',
            'blank': 'Password cannot be empty.',
            'min_length': 'Password too short.',
        },
    )

    class Meta:
        model = get_user_model()
        fields = (
            'email',
            'username',
            'first_name',
            'last_name',
            'full_name',
            'password'
        )
        extra_kwargs = {
            'first_name': {'write_only': True},
            'last_name': {'write_only': True},
        }

    def create(self, validated_data):
        """Create and return a new user."""

        user = get_user_model().objects.create_user(
            username=validated_data.pop('username'),
            email=validated_data.pop('email'),
            password=validated_data.pop('password'),
            **validated_data
        )
        return user

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Profile
        fields = [
            'url',
            'bio',
            'birth_date',
            'avatar_url',
            'cover_url',
            'user'
        ]

在向http://localhost:8000/profiles/1/ 发送 GET 请求时,我试图得到如下响应:

{
    "user": {
      "url": "http://localhost:8000/users/1/",
      "email": "cthulhu@gmail.com",
      "username": "cthulhu",
      "fullName": "Marcos Rios"
    },
    "url": "http://localhost:8000/v1/profiles/1/",
    "avatarUrl": "assets/images/avatars/rick.jpeg",
    "bio": "Hincha de River Plate!",
    "birthDate": "1991-02-05",
    "coverUrl": "assets/images/monumental.jpg"
}

但是,相反,我收到了没有用户数据的响应。像这样的:

{
    "url": "http://localhost:8000/v1/profiles/1/",
    "avatarUrl": "assets/images/avatars/rick.jpeg",
    "bio": "Hincha de River Plate!",
    "birthDate": "1991-02-05",
    "coverUrl": "assets/images/monumental.jpg"
}

它仅从配置文件视图返回配置文件模型信息。我的代码有什么问题?

【问题讨论】:

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


    【解决方案1】:

    您正在尝试序列化 Profile 实例,因此您应该使用 user 而不是 profile

    class ProfileSerializer(serializers.HyperlinkedModelSerializer):
        user = UserSerializer(read_only=True)
    
        class Meta:
            model = Profile
            depth = 1
            fields = ['url', 'avatar_url', 'bio', 'birth_date', 'cover_url', 'user']

    注意:这不是反向关系

    【讨论】:

    • 这是我尝试的第一件事,但我得到了相同的响应(没有用户数据)
    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 2017-06-23
    • 1970-01-01
    • 2018-02-10
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多