Thursday, 23 May 2019

Django Rest Framework ModelSerializer custom serializer field to_internal_value doesn't save to object

I have model and serializer, there is ArrayField(postgres) in that model.

Now I wanted to create a serializer field that will receive list [1,2] and save it to object, but for a list and detail in serializer to show a list of JSON objects.

Model:

class User(models.Model):
    email = models.EmailField('Email', unique=True, blank=False)
    full_name = models.CharField(
        'Full name', max_length=150, blank=True, null=True)
    roles = ArrayField(
        models.PositiveSmallIntegerField(),
        default=list,
        blank=True
    )

Serializer:

class ArraySerializerField(ListField):

    def __init__(self, queryset, serializer_class):
        super(ArraySerializerField, self).__init__()
        self.queryset = queryset
        self.serializer_class = serializer_class

    def to_representation(self, value):
        if value:
            qs = self.queryset.filter(pk__in=value)
            return self.serializer_class(qs, many=True).data

        return []

    def to_internal_value(self, value):
        super(ArraySerializerField, self).to_internal_value(value)
        print(value)  # [1, 2]
        return value


class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = ArraySerializerField(queryset=Role.objects.all(), serializer_class=RoleSerializer)

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        print(validated_data) 
        # {'email': 'test@test.com', 'full_name': 'Test', 'roles': []}
        user = super(UserSerializer, self).create(validated_data)

        return user

Now when I do list or detail request, everything is ok, I get a list of roles as JSON.

But when I try to POST data and send with this data:

{
  "email": "test@test.com",
  "full_name": "Test",
  "roles": [1, 2]
}

validated_data in create method shows roles always as [] and object is saved without roles, but print from to_internal_value shows [1, 2].

What am I doing wrong? It should save sent data because to_internal_value works fine.



from Django Rest Framework ModelSerializer custom serializer field to_internal_value doesn't save to object

No comments:

Post a Comment