updated July 27, 2020

Django REST framework serializers tips

Django REST framework serializers convert data dictionary into object and back. They are similar to Django forms: serializer provide type conversion and data validation.

1. Object to data and back

Convert object to data dict:
serializer = OrderSerializer(instance=order)  # pass object as instance parameter
serializer.data  # get data dict for JSON response
Create object from data dict, for example from the request data:
serializer = OrderSerializer(data=request.data)  # pass data as data parameter

# serializer.validated_data is accessible after this call
serializer.is_valid(raise_exception=True)

instance = serializer.create()  # create object and return object
Please note that type conversion is made for validated_data

Tip. How to return object without saving into the database: override Serializer.create(**validated_data) method to return cls(**validated_data) without saving.

2. Specify data parameter name for the object field

Use source parameter of the serializer field:
class OrderSerializer(serializers.Serializer):

    # map Order customer_id field to the customer data parameter
    customer_id = serializers.CharField(max_length=100, source="customer")

3. Pass parameters into serializer.save()

If object requires fields set to create it but they are not in the request data:
serializer = OrderSerializer(data=request.data)
serializer.save(user=request.user)  # pass current session user