django rest serializer to_representation失败

nwlqm0z1  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(101)

我在django rest框架和它的序列化器上瞎折腾,在重写create方法时遇到了一个错误。
串行器

class AdddTestModel(serializers.Serializer):
name = serializers.CharField()
score = serializers.FloatField()
score2 = serializers.FloatField()
song = serializers.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):
    serializer = AdddTestModel(data=request.data)
    if serializer.is_valid():
        serializer.save()
        
        print(serializer.data)
        return Response("hello", status=status.HTTP_201_CREATED)
    return Response("Error", status=status.HTTP_401_UNAUTHORIZED)

当我使用modelSerializer时,一切都正常工作,但我想尝试serializer.Serializer。
我知道create方法正在工作,因为TestModel对象被持久化到我的数据库中。
错误似乎来自to_representation方法,具体来说,

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\theFirstView\api\views.py", line 53, in addTestModel
    print(serializer.data)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\serializers.py", line 555, in data
    ret = super().data
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\serializers.py", line 253, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\thoma\Documents\venv\lib\site-packages\rest_framework\serializers.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'

我知道使用serializers.ModelSerializer在这里更有意义,但我只是想知道是否有任何特定的原因可以使用serializers.ModelSerializer而不是serializers.serializer

oalqel3c

oalqel3c1#

您在创建中正确地处理了业务模型的有效负载参数,但在序列化响应时没有做完全相反的事情。你必须明确定义你想要song id作为song-field的值。

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

编辑:
当然,你可以使用serializers.PrimaryKeyRelatedField作为song-field来完成这个转换,而不需要任何额外的麻烦。它将在序列化时直接在验证数据中给予模型对象,并在序列化时将pk作为值。

相关问题