首页 > 解决方案 > 序列化程序和json响应的奇怪错误

问题描述

我有一个配置文件模型,我使用“ all ”序列化和设置字段。问题是,当我运行它时,我收到以下错误:

AttributeError at /api/accounts/profile/
'User' object has no attribute 'following'

我尝试手动设置字段并得到相同的错误,但是当我从字段中删除以下内容时,它会正常运行并且我得到正常的 JSON 响应,但是所有字段都显示为 null 而不是我在管理面板中设置的数据。

{
    "pk": 2,
    "date_of_birth": null,
    "bio": null,
    "profile_photo": null,
    "sex": null,
    "type_of_body": null,
    "feet": null,
    "inches": null,
    "lives_in": null
}

下面是应用程序其余部分的代码

模型.py

class Profile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
    date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB")
    bio = models.TextField(max_length=500, null=True, blank=True)
    profile_photo = models.CharField(blank=True, null=True, max_length=300)
    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)

序列化程序.py

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = '__all__'
        read_only_fields = ('pk', 'user', 'following', 'height')

视图.py

class CurrentUserProfileAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        serializer = ProfileSerializer(request.user)
        return Response(serializer.data)

网址.py

urlpatterns = [
    url(r'^profile/$', CurrentUserProfileAPIView.as_view(), name="my_profile")
]

标签: pythondjangodjango-rest-framework

解决方案


request.usersettings.AUTH_USER_MODEL返回(或AnonymousUser任何未经身份验证的用户)的实例- 请求用户,但您正在尝试使用模型的序列化程序ProfileProfileSerializer)对其进行序列化。

由于用户没有提到的Profile模型属性,所有字段都被序列化为null. 而pkuser.pk,它存在于任何 Django 模型实例上(总是指使用的公钥)。


推荐阅读