我正在研究Django REST框架及其序列化程序,并且在覆盖Create方法时遇到错误.

串行器

class AdddTestModel(串行器s.Serializer):
name = 串行器s.CharField()
score = 串行器s.FloatField()
score2 = 串行器s.FloatField()
song = 串行器s.IntegerField()


def create(self, validated_data):
    print(validated_data["song"])
    song = Song.objects.get(id=validated_data["song"])
    print(song)
    instance = TestModel.objects.create(name=validated_data["name"], score = validated_data["score"], score2 = validated_data["score2"], song = song)
    return instance


def to_representation(self, instance):
    representation = super().to_representation(instance)
    return representation

@api_view(["POST"])
def addTestModel(request):
    串行器 = AdddTestModel(data=request.data)
    if 串行器.is_valid():
        串行器.save()
        
        print(串行器.data)
        return Response("hello", status=status.HTTP_201_CREATED)
    return Response("Error", status=status.HTTP_401_UNAUTHORIZED)

I had everything working correctly when I was using a modelSerializer, but wanted to experiment with 串行器.Serializer.

我知道当TestModel对象被持久化到我的数据库中时,Create方法正在工作.

错误似乎来自TO_表示方法,具体地说

representation = super().to_representation(instance)

我收到的错误如下所示

Internal Server Error: /api/addTest/
Traceback (most recent call last):
  File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view
    return view_func(*args, **kwargs)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\django\views\generic\base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "C:\Users\thoma\Documents\realestate\theFirst观\api\views.py", line 53, in addTestModel
    print(串行器.data)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\串行器s.py", line 555, in data
    ret = super().data
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\串行器s.py", line 253, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\串行器s.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\fields.py", line 915, in to_representation
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Song'

I know using 串行器s.ModelSerializer makes more sense here, but i'm just wondering if there is any specific reason why this is working with 串行器s.ModelSerializer but not 串行器s.串行器

推荐答案

您在Create中正确地处理了业务模型的有效负载参数,但在序列化响应时却没有进行完全相反的操作.您必须显式定义您想要的歌曲id作为Song-field的值.

def to_representation(self, instance):
    return {
         "song": instance.song.id,
         # rest ...
    }

编辑:

当然,您可以使用序列化程序.PrimaryKeyRelatedfield for Song-field来完成此转换,而不需要任何额外的工作.它会在反序列化时直接在已验证的数据中给出模型对象,在序列化时给出Pk作为值.

Django相关问答推荐

如何在Django模型mixin字段定义中引用模型名称?

对象Django API中的对象

在Django的反向函数中添加动态URL

创建用户/将用户登录到客户端服务器的标准OAuth/OIDC流程是什么?

如何将Django项目连接到容器化的PostgreSQL数据库?

将所有守护用户对象权限从一个Django用户重新分配给另一个Django用户

Django:作为模型中的列表元素的字段

注册新用户时,对象没有属性';is_active';错误:';NoneType';对象没有属性

Django rest框架:自定义对象权限不起作用

NoneType对象没有属性保存Django

Django 视图 - 首先从调用应用程序的目录加载模板

Django:通过manage.py使用服务器和gunicorn等其他服务器之间的区别.哪个更好?

Django Calendar日历小部件?

在 Django 中,您可以向查询集添加方法吗?

在 Django 管理员中嵌套内联?

is_valid() vs clean() Django 表单

ImportError:无法导入设置

带有消息判断的 Django/Python assertRaises

模拟 Django 查询集以测试采用查询集的函数

AUTH_USER_MODEL 指的是尚未安装和创建的模型 .. AbstractUser 模型无法登录