Django rest framework 尝试获取序列化程序` ProfileSerializer上字段` bio`的值时获取AttributeError`
我正在尝试为用户配置文件设置api,但我得到了 “尝试获取序列化程序探查器serializer上的字段Django rest framework 尝试获取序列化程序` ProfileSerializer上字段` bio`的值时获取AttributeError`,django-rest-framework,Django Rest Framework,我正在尝试为用户配置文件设置api,但我得到了 “尝试获取序列化程序探查器serializer上的字段bio的值时,获取了AttributeError。 序列化程序字段的名称可能不正确,并且与int实例上的任何属性或键都不匹配。 原始异常文本为:“int”对象没有属性“bio”。“ models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delet
bio
的值时,获取了AttributeError。
序列化程序字段的名称可能不正确,并且与int
实例上的任何属性或键都不匹配。
原始异常文本为:“int”对象没有属性“bio”。“
models.py
class Profile(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(User, null=True, blank=True, upload_to="images/")
URL1 = models.CharField(max_length=120)
URL2 = models.CharField(max_length=120)
def __str__(self):
return str(self.user)
序列化程序.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ("bio", "profile_pic", "URL1", "URL2")
View.py
@api_view(['GET'])
def current_user(request):
user = request.user
try:
user_detail = user.id
except item_detail.DoesNotExist:
return Response({'message': 'The Item does not exist'}, status=status.HTTP_404_NOT_FOUND)
Profile_serializer = ProfileSerializer(user_detail)
return Response(Profile_serializer.data)
您正在尝试将实例传递给ProfileSerializer,而不是概要文件实例。
这样试试
from django.shortcuts import get_object_or_404
@api_view(['GET'])
def current_user(request):
user = request.user
profile = get_object_or_404(Profile, user=user)
Profile_serializer = ProfileSerializer(profile)
return Response(Profile_serializer.data)
您正在尝试将实例传递给ProfileSerializer,而不是概要文件实例。
这样试试
from django.shortcuts import get_object_or_404
@api_view(['GET'])
def current_user(request):
user = request.user
profile = get_object_or_404(Profile, user=user)
Profile_serializer = ProfileSerializer(profile)
return Response(Profile_serializer.data)