Django REST API:通过user_id获取用户及资料接口报错求助
解决Django REST Framework中获取User及Profile时的TypeError问题
错误原因分析
报错TypeError: 'User' object is not iterable由两个问题导致:
- 你将
User对象直接传给了针对User_profile模型的ProfileSerializer,序列化器只能处理对应模型的实例; - 错误设置了
many=True参数,该参数仅用于序列化多个对象(如QuerySet集合),单个对象无需添加。
分步修复方案
1. 新增用户序列化器
要返回User的信息,需先创建针对Django内置User模型的序列化器。修改serializer.py:
from rest_framework import serializers from django.contrib.auth.models import User from .models import User_profile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'last_name'] # 按需选择需要返回的字段 class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User_profile fields = "__all__"
2. 修复视图逻辑
修改api_views.py,先通过user_id获取User对象,再通过OneToOne关联获取对应的User_profile,最后分别序列化并合并返回数据:
from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from django.contrib.auth.models import User from .serializer import UserSerializer, ProfileSerializer from .models import User_profile class ProfileAPI(APIView): def get(self, request, *args, **kwargs): # 获取User对象 user = get_object_or_404(User, id=kwargs['user_id']) # 通过OneToOne关联获取对应的Profile profile = get_object_or_404(User_profile, user=user) # 分别序列化User和Profile user_serializer = UserSerializer(user) profile_serializer = ProfileSerializer(profile) # 合并数据返回 response_data = { 'user': user_serializer.data, 'profile': profile_serializer.data } return Response(response_data)
3. 修正URL路径参数
为让Django自动验证参数类型,避免非整数的user_id导致错误,修改api_urls.py:
from django.urls import path from . import api_views urlpatterns = [ path('profile/<int:user_id>', api_views.ProfileAPI.as_view(), name="profile") ]
额外优化(可选)
如果希望在Profile序列化器中直接包含User信息,可以修改ProfileSerializer,通过嵌套UserSerializer实现:
class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() # 嵌套用户序列化器 class Meta: model = User_profile fields = "__all__"
此时视图可简化为只序列化Profile,响应会自动包含关联的User数据:
class ProfileAPI(APIView): def get(self, request, *args, **kwargs): profile = get_object_or_404(User_profile, user_id=kwargs['user_id']) profile_serializer = ProfileSerializer(profile) return Response(profile_serializer.data)
内容的提问来源于stack exchange,提问作者Anuragverma2804
相关产品推荐
相关产品推荐

