In Django, where does the "data" field come from in the Serializer class?

67 Views Asked by At

I see in a bunch of django code, especially in viewsets, that when serializer is initialized like the following:

class UserViewSet(viewsets.ModelViewSet):
    """
    A viewset that provides the standard actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
    @action(detail=True, methods=['post'])
    def set_password(self, request, pk=None):
        user = self.get_object()
        **serializer = PasswordSerializer(data=request.data)**

the data argument is always being passed in the instantiation of a Serializer instance. But I feel like I have been researching django documentation everywhere and I can't seem to find a reference to this data argument. I really want to know what exactly is data doing here, where does it come from, why is information about it so hidden?

I tried researching the official django rest framework documentation, as well as scoured several Medium articles to no avail.

2

There are 2 best solutions below

0
Vikrantkumar On

In Django REST framework (DRF), the data argument you're referring to is commonly used when instantiating a serializer. This argument represents the data that you want to serialize or validate.

serializer = PasswordSerializer(data=request.data)

PasswordSerializer is a serializer class, and request.data is the input data that you want to validate and/or serialize using this serializer.

request.data: This is typically used in Django REST framework views to access the incoming data from a request. It's a dictionary-like object containing the parsed data from the request payload. In the case of a POST request, this would typically be the data sent in the request body.

When you instantiate a serializer with data=request.data, you are essentially telling the serializer to operate on this input data. The serializer will then use its defined fields and validation rules to process this data.

0
Tanveer On

You can find these functions in serializers.py that comes from package

def create(self, validated_data):
    return [
        self.child.create(attrs) for attrs in validated_data
    ]

def save(self, **kwargs):
    """
    Save and return a list of object instances.
    """
    # Guard against incorrect use of `serializer.save(commit=False)`
    assert 'commit' not in kwargs, (
        "'commit' is not a valid keyword argument to the 'save()' method. "
        "If you need to access data before committing to the database then "
        "inspect 'serializer.validated_data' instead. "
        "You can also pass additional keyword arguments to 'save()' if you "
        "need to set extra attributes on the saved model instance. "
        "For example: 'serializer.save(owner=request.user)'.'"
    )

    validated_data = [
        {**attrs, **kwargs} for attrs in self.validated_data
    ]

    if self.instance is not None:
        self.instance = self.update(self.instance, validated_data)
        assert self.instance is not None, (
            '`update()` did not return an object instance.'
        )
    else:
        self.instance = self.create(validated_data)
        assert self.instance is not None, (
            '`create()` did not return an object instance.'
        )

    return self.instance

def is_valid(self, *, raise_exception=False):
    # This implementation is the same as the default,
    # except that we use lists, rather than dicts, as the empty case.
    assert hasattr(self, 'initial_data'), (
        'Cannot call `.is_valid()` as no `data=` keyword argument was '
        'passed when instantiating the serializer instance.'
    )

    if not hasattr(self, '_validated_data'):
        try:
            self._validated_data = self.run_validation(self.initial_data)
        except ValidationError as exc:
            self._validated_data = []
            self._errors = exc.detail
        else:
            self._errors = []

    if self._errors and raise_exception:
        raise ValidationError(self.errors)

    return not bool(self._errors)