django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Serializing a dict using "source" does not work

Open mcosti opened this issue 4 years ago • 6 comments

Checklist

  • [ x] Raised initially as discussion #...
  • [ x] This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • [x ] I have reduced the issue to the simplest possible case.
class CourseSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    key = serializers.CharField(source="courseKey")

data = {'id': 1, 'courseKey': 'abc'}

serializer = CourseSerializer(data=data)
serializer.is_valid(raise_exception=True)

>>> rest_framework.exceptions.ValidationError: {'key': [ErrorDetail(string='This field is required.', code='required')

I've spent around 2 hours browing the documentation and google for a fix, but meanwhile I will just end up using a different serializing library.

Thanks for the assistance

mcosti avatar Sep 27 '22 16:09 mcosti

I think you've got the arguments the wrong way around. (Yes it's easily confused)

class CourseSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    courseKey = serializers.CharField(source="key")

lovelydinosaur avatar Sep 28 '22 11:09 lovelydinosaur

Thanks for your answer. The output of this serializer returns still

{"id": 1, "courseKey": "abc"}

While I would expect it to return

{"id": 1, "key": "abc"}

mcosti avatar Sep 28 '22 13:09 mcosti

FWIW this still doesn't appear to work.

My use case is very similar to @mcosti's in the first post.

class CourseSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    key = serializers.CharField(source="courseKey")

data = {'id': 1, 'courseKey': 'abc'}

serializer = CourseSerializer(data=data)
serializer.is_valid(raise_exception=True)

I want the serialized output to contain the key field, with its source being the courseKey field in the input dictionary. The docs seem to point to that being a supported use case with the source argument on a serializer field, but in practice it fails.

dkambersky avatar Nov 09 '23 12:11 dkambersky

Yeah it still doesn't work. @tomchristie marked it as complete, but I didn't bother and just used pydantic instead

mcosti avatar Nov 09 '23 12:11 mcosti

Additionaly even workaround or another way does not work for me. According to https://www.django-rest-framework.org/api-guide/fields/#source , the method could be used as source value.

The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').

But my academic purpose code to prove that it is ok is below and does not work either.

from rest_framework import serializers
class My(serializers.Serializer):
     id = serializers.IntegerField()
     key = serializers.CharField(source="get_key")
     def get_key(self):
         print("no call")
         return self.data["courseKey"]
data = {"id": 1, "courseKey": "asd"}
ser = My(data=data)
ser.is_valid()  # False
ser.errors  # {'key': [ErrorDetail(string='Toto pole je třeba vyplnit.', code='required')]}

I also tried the dotted notation, for that purpose I tried to use dataclass ...

from dataclasses import dataclass, field
@dataclass
class Row:
     id: int = field()
     courseKey: str = field()
class My(serializers.Serializer):
    id = serializers.IntegerField()
    key = serializers.CharField(source="courseKey")
data = Row(id=1, courseKey="ads")
ser = My(data=data)
ser.is_valid()  # False
ser.errors  # {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got Row.', code='invalid')]}

So nothing from documentation works for me.

notice: it seems that not all the things form internal django or drf is translated into czech, but it is ok, please focus on the "source" does not work according to doc.

michalnik avatar Nov 10 '23 07:11 michalnik

Ok, I find that I was wrong when I want to serialize internally computed data and put it into the response it is wrong to do it this way. The right way is.

from rest_framework import serializers
class My(serializers.Serializer):
     id = serializers.IntegerField()
     key = serializers.CharField(source="courseKey")
data = {"id": 1, "courseKey": "asd"}
ser = My(data)
# you cannot call this, because the data are supposed already be validated - ser.is_valid()
# IMHO, the source kwarg is intended to use with trusted source data, from database model of django...
# Still there is type casting during serialization called,  IMHO to_representation is called for every field
return Response(data=ser.data)  # I am not sure with this Response, but ser.data is ok

michalnik avatar Nov 10 '23 08:11 michalnik