我的个人资料对象未在用户序列化程序中序列化

时间:2019-11-23 15:19:59

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

我正在使用Django rest auth来验证我的用户,效果很好。我的模型的设置方式是,我有用于身份验证的自定义用户模型,也有通过信号创建的配置文件模型。

我希望在通过其URL获取用户时,该用户的配置文件也称为用户中的对象。

我的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):
    '''
    Note:
    profile photo is expecting photos link gotten from cloudnairy from the frontend
    - The height is calculated in feets and inches
    - Need to sort out location (lives in)
    - Need to add an age function
    - Need to add achievemnet as a foreign field 
    - Need to add education also as a foreign field
    - Add follow functionality
    '''
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    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)
    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):

    profile = ProfileSerializer(read_only=True)

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

view.py

class ListUsersView(APIView):

    permission_classes = [AllowAny]

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

urls.py

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

我得到的JSON响应

[
    {
        "pk": 1,
        "email": "opeyemiodedeyi@gmail.com",
        "fullname": "opeyemiodedeyi"
    },
    {
        "pk": 2,
        "email": "odedeyiopeyemi94@gmail.com",
        "fullname": "opeyemi odedeyi"
    }
]

如何使个人资料显示在响应中?

1 个答案:

答案 0 :(得分:1)

方法1

使用source (DRF doc)自变量

std::static_pointer_cast

由于配置文件用户具有反向关系,因此您需要指定反向查找,即 {{1} }

方法2

更改模型中的related_name (Django doc)

class CustomUserDetailsSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True, source="profile_set")

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

建议的更改

profile_set

参考

  1. What is reverse relationship?
  2. Django: Many-To-One Relation