[Django]-Django Rest Framework serializers.DictField constraint on possible keys

2👍

Django Rest Framework provides a DictField serializer field that can be used to handle dictionaries in your API.

You can add a constraint on the possible keys of the dictionary by subclassing DictField and overriding the to_internal_value() method to perform the necessary validation.

Have a look at this example,

from rest_framework import serializers

class ConstrainedDictField(serializers.DictField):
    def to_internal_value(self, data):
        # Perform validation on the keys of the dictionary here
        if set(data.keys()) != {"key1", "key2"}:
            raise serializers.ValidationError("Invalid keys for dictionary.")
        return super().to_internal_value(data)

You can then use the ConstrainedDictField in your serializer like this:

class MySerializer(serializers.Serializer):
    my_dict = ConstrainedDictField()

It will only accept dictionary with key key1 and key2.

👤Arjun

0👍

Have a look at this https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

The Serializer class is itself a type of Field, and can be used to
represent relationships where one object type is nested inside
another.

class UserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    username = serializers.CharField(max_length=100)

class CommentSerializer(serializers.Serializer):
    user = UserSerializer()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

Leave a comment