[Django]-How to user Django REST serializer do validation on reserved key?

3πŸ‘

βœ…

@cezar Thank you very much!
The solution is so simple! I was confused at the early time. Because the given solutions are using ModelSerializer by that you have to put fields and coupling with model properties.

In my example is bare plain Serializer I don’t need any of them.

From now on I would attacking this kind of problem by Serializer class

class FacebookReactionSerializer(serializers.Serializer):
    """
    value serializer the inner most of the payload
    """
    item = serializers.CharField()
    verb = serializers.CharField()
    reaction_type = serializers.CharField()
    created_time = serializers.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(4086831600)]
    )  # Limit the maximum epoch to 2099 July 4th 7:00AM
    post_id = serializers.CharField(max_length=40)
    parent_id = serializers.CharField()

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass


FacebookReactionSerializer._declared_fields["from"] = FromSerializer()

Here is my debugging lines

(Pdb) serializer
FacebookReactionSerializer(data={'item': 'reaction', 'verb': 'add', 'reaction_type': 'like', 'created_time': 1516183830, 'post_id': '1331351323541869_1844740022202994', 'from': {'name': 'Krittuch Onnom', 'id': '1639217166122728'}, 'parent_id': '1331351323541869_1844740022202994'}):
    item = CharField()
    verb = CharField()
    reaction_type = CharField()
    created_time = IntegerField(validators=[<rest_framework.compat.MinValueValidator object>, <rest_framework.compat.MaxValueValidator object>])
    post_id = CharField(max_length=40)
    parent_id = CharField()
    from = FromSerializer():
        name = CharField()
        id = CharField()
(Pdb) serializer.is_valid()
True
πŸ‘€joe

Leave a comment