首页 > 解决方案 > 为我的配置文件序列化程序数据而不是实际数据获取 null

问题描述

我正在使用 Django-rest-auth 对我的用户进行身份验证,效果很好。我的模型是如何设置的,我有用于身份验证的自定义用户模型,并且我还有一个配置文件模型,该模型在创建用户时使用信号创建。

我希望当用户在其 URL 中被获取时,该用户的配置文件也会显示出来,并且我已经通过了序列化程序。

问题:我得到 null 而不是实际数据

我的models.py(我没有包括一些模型,比如用户管理器、技能等,因为我觉得它们不相关)

class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(max_length=254, unique=True)
    fullname = models.CharField(max_length=250)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['fullname']

    objects = UserManager()


class Profile(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles')
    date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True)
    bio = models.TextField(max_length=500, blank=True, null=True)
    profile_photo = models.CharField(blank=True, max_length=300, null=True)
    skills = models.ManyToManyField(Skill, related_name='skills')
    sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True)
    type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True)
    feet = models.PositiveIntegerField(blank=True, null=True)
    inches = models.PositiveIntegerField(blank=True, null=True)
    lives_in = models.CharField(max_length=50, blank=True, null=True)
    updated_on = models.DateTimeField(auto_now_add=True)

serializers.py 代码

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = "__all__"

        read_only_fields = ('pk',)


class CustomUserDetailsSerializer(serializers.ModelSerializer):

    profiles = ProfileSerializer(read_only=True)

    class Meta:
        model = User
        fields = ('pk', 'email', 'fullname', 'profiles')
        read_only_fields = ('email', 'fullname', 'profiles')

视图.py

class ListUsersView(APIView):

    permission_classes = [AllowAny]

    def get(self, request):
        user = User.objects.all()
        serializer = CustomUserDetailsSerializer(user, many=True)
        return Response(serializer.data)

网址.py

url(r'^list-users/$', ListUsersView.as_view(), name='list-users'),

我得到的 JSON 响应

[
    {
        "pk": 1,
        "email": "opeyemiodedeyi@gmail.com",
        "fullname": "opeyemi odedeyi",
        "profiles": {
            "date_of_birth": null,
            "bio": null,
            "profile_photo": null,
            "sex": null,
            "type_of_body": null,
            "feet": null,
            "inches": null,
            "lives_in": null
        }
    }
]

如何让配置文件显示在响应中?

标签: pythondjangodjango-rest-frameworkdjango-rest-auth

解决方案


我想问题出在你的CustomUserDetailsSerializer. 您与用户和配置文件有一对多的关系,但您没有profiles在序列化程序的属性中明确告诉它。您必须将many=True参数传递给ProfileSerializer

class CustomUserDetailsSerializer(serializers.ModelSerializer):

    profiles = ProfileSerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ('pk', 'email', 'fullname', 'profiles')
        read_only_fields = ('email', 'fullname', 'profiles')

但我很好奇你为什么要使用一对多的关系。您可以使用 OneToOneField 明确告诉一个用户只能拥有一个配置文件。但我不熟悉你的情况,所以这只是我的建议。


推荐阅读