无法从另一个模型中获取图像字段“'ImageFileDescriptor' 类型的 /api/users/profile 参数中的 TypeError 不可迭代”

问题描述

我正在使用 django 用户模型 创建了 UserExtended 模型用于存储用户的额外详细信息,以便我可以存储额外的用户数据并在需要时调用它们

这是模型

class UserExtended(models.Model):
    extended_id = models.AutoField(primary_key=True,editable=False)
    avatar = models.ImageField(null=True,blank=True)
    user = models.OnetoOneField(User,on_delete=models.CASCADE,null=False)
    created_at = models.DateTimeField(auto_Now_add=True)
    updated_at = models.DateTimeField(auto_Now=True)

查看功能是:

@api_view(['GET'])
def get_user_profile(request):
    user = request.user
    serializer = UserSerializer(user,many=False)
    return Response(serializer.data)

序列化器:

class UserSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField(read_only=True)
    isAdmin = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.ImageField(source=UserExtended.avatar,read_only=True)

    class Meta:
        model = User
        fields = ['id','username','email','name','avatar','isAdmin']

    def get_name(self,obj):
        name = obj.first_name
        if name == '':
            name = obj.email
        return name

    def get_isAdmin(self,obj):
        return obj.is_staff

我想我应该得到这样的 api 响应

GET http://localhost:8000/api/users/profile

HTTP/1.1 200 OK
Date: Mon,14 Jun 2021 13:45:13 GMT
Server: WsgiServer/0.2 cpython/3.9.2
Content-Type: application/json
vary: Accept
Allow: OPTIONS,GET
x-frame-options: DENY
Content-Length: 103
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

{
  "id": 1,"username": "superuser","email": "superuser@test.com","name": "superuser@test.com","avatar": "/images/Capture.PNG"
  "isAdmin": true
}

不工作 但我收到此错误 请帮帮我

GET http://localhost:8000/api/users/profile

HTTP/1.1 500 Internal Server Error
Date: Mon,14 Jun 2021 13:48:50 GMT
Server: WsgiServer/0.2 cpython/3.9.2
Content-Type: text/plain; charset=utf-8
x-frame-options: DENY
Content-Length: 21746
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin

TypeError at /api/users/profile
argument of type 'ImageFileDescriptor' is not iterable

Request Method: GET
Request URL: http://localhost:8000/api/users/profile
Django Version: 3.2.4
Python Executable: D:\work environment\Django_Api\codersavvy\Scripts\python.exe
Python Version: 3.9.2
Python Path: ['D:\\work environment\\Django_Api\\codersavvy','C:\\Users\\S\\AppData\\Local\\Programs\\Python\\python39\\python39.zip','C:\\Users\\S\\AppData\\Local\\Programs\\Python\\python39\\DLLs','C:\\Users\\S\\AppData\\Local\\Programs\\Python\\python39\\lib','C:\\Users\\S\\AppData\\Local\\Programs\\Python\\python39','D:\\work environment\\Django_Api\\codersavvy','D:\\work environment\\Django_Api\\codersavvy\\lib\\site-packages']
Server time: Mon,14 Jun 2021 13:48:50 +0000
Installed Applications:
['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','blog.apps.BlogConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback (most recent call last):
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\exception.py",line 47,in inner
    response = get_response(request)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\base.py",line 181,in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\decorators\csrf.py",line 54,in wrapped_view
    return view_func(*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\views\generic\base.py",line 70,in view
    return self.dispatch(request,*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 509,in dispatch
    response = self.handle_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 469,in handle_exception
    self.raise_uncaught_exception(exc)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 480,in raise_uncaught_exception
    raise exc
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\views.py",line 506,in dispatch
    response = handler(request,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\decorators.py",line 50,in handler
    return func(*args,**kwargs)
  File "D:\work environment\Django_Api\codersavvy\blog\views.py",line 32,in get_user_profile
    return Response(serializer.data)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 548,in data
    ret = super().data
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 246,in data
    self._data = self.to_representation(self.instance)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 500,in to_representation
    for field in fields:
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 361,in _readable_fields
    for field in self.fields.values():
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\django\utils\functional.py",line 48,in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 349,in fields
    for key,value in self.get_fields().items():
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 1034,in get_fields
    extra_kwargs,hidden_fields = self.get_uniqueness_extra_kwargs(
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 1389,in get_uniqueness_extra_kwargs
    model_fields = self._get_model_fields(
  File "D:\work environment\Django_Api\codersavvy\lib\site-packages\rest_framework\serializers.py",line 1472,in _get_model_fields
    if '.' in source or source == '*':

请帮帮我

解决方法

您应该使用 SerializerMethodField

avatar = serializers.SerializerMethodField()

def get_avatar(self,obj):
    return obj.userextended.avatar.url

class Meta:
    model = User
    fields = ['id','username','email','name','avatar','isAdmin']