Home > Back-end >  Serialize JSON with a python keyword using the django-rest-framework
Serialize JSON with a python keyword using the django-rest-framework

Time:05-04

I have a django app (using the django-rest-framework) that needs to serialize and deserialize JSON payloads with the python keyword "import" as one of the fields. To prevent conflicts in the model, I can call the field import_flag and use the source option in the ModelSerializer.

models.py

class MyModel(model.Model):
    import_flag = models.BooleanField(verbose_name='Import')

But (for obvious reasons) I cannot use the import keyword as to create a JSON field named "import" like so.

serializers.py

    class MyModelSerializer(serializer.ModelSerializer):
        import = serializers.BooleanField(source='import_flag')
        
        def Meta:
            model = MyModel

This field is present in the JSON I consume from a third-party's RESTful API and I also need to serialize it and send it back to the same third-party.

Is there something like a destination option for the Django-rest-framework ModelSerializer class? I have been unable to find anything in the documentation.

CodePudding user response:

you can do this by overriding to_internal_value and to_representation in your serializer.

class MyModelSerializer(serializers.ModelSerializer):
    def Meta:
        model = MyModel
        fields = ...

    def to_internal_value(self, data):
        instance = super(MyModelSerializer, self).to_internal_value(data)
        instance.import_flag = data.get('import')

    def to_representation(self, instance):
        data = super(MyModelSerializer, self).to_representation(instance)
        data['import'] = instance.import_flag

CodePudding user response:

You can leverage the to_representation method to add extra fields when serializing back:

def to_representation(self, instance):
    attrs = super().to_representation(instance)
    attrs['import'] = attrs['import_flag']
    ...
    return attrs

You can also override the __init__ of your serializer and try adding the import field there:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['import'] = serializers.BooleanField(source='import_flag')
  • Related