DEV Community

Sajal Shrestha
Sajal Shrestha

Posted on

1

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 😊

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay