DEV Community

Sajal Shrestha
Sajal Shrestha

Posted on

Django Rest: use reserved keywords as a field in serializer

Recently We've come across a problem at work, where we had to serialize the request payload that has some clauses like and, in, class etc.

Consider the following request payload that needs to be serialized:

{
    "values": [ "21234" ],
    "and": true,
    "count": 200,
    "year": 2020
}
Enter fullscreen mode Exit fullscreen mode

Django-Rest Serializer class provides a method get_fields that allows us to dynamically modify the fields. So we can use this method to modify the fields as follow:

from rest_framework import serializers

class DemoSerializer(serializers.Serializer):
    values = serializers.ListField(child=serializers.CharField(), allow_empty=True)
    and_ = serializers.BooleanField() # avoid naming conflicts
    count = serializers.IntegerField()
    year = serializers.IntegerField()

    def get_fields(self):
        fields = super().get_fields()
        and_ = fields.pop('and_') # Dynamically modify field
        fields['and'] = and_
        return fields
Enter fullscreen mode Exit fullscreen mode

Now, we can use DemoSerializer to serialize the payload:

import json
from rest_framework.exceptions import ValidationError

payload = """
{
    "values": [ "21234" ],
    "and": true,
    "count": 200,
    "year": 2020
}
"""
serializer = DemoSerializer(data=json.loads(payload))
try:
    serializer.is_valid(raise_exception=True) # Perform validation
except ValidationError as error:
    print(error)
else:
    validated_data = serializer.validated_data 
    print(validated_data)
Enter fullscreen mode Exit fullscreen mode

Output:

OrderedDict([('values', ['21234']), ('count', 200), ('year', 2020), ('and', True)])
Enter fullscreen mode Exit fullscreen mode

Hope this helps 😊

Top comments (0)