Skip to content
Advertisement

DRF Serializer – Accept field but don’t use it in `create` or `update`

I have a model Message that has a FileField. My API accepts files in Base64 encoding so they can be sent alongside other data.

To know a filename and an extension, there is one more field attachment_filename in the serializer that is not a model field. It is used inside Base64Field.

I want to be able to validate if there are both attachment_filename , attachment, or none of them.

The problem is that if the attachment_filename is read-only, it is not present in validatedata variable.

On the other hand, if it’s required=False, allow_null=True, the serializer raises an error when creating a message:

JavaScript

Code:

JavaScript

How to make it work?

EDIT

I managed to make it work by adding

JavaScript

before validate method return but that seems to be too “dirty”.

Advertisement

Answer

You should handle this behavior in serializer.save method, for example, you can pop it from validated_data like that:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement