I'm using relation database which is having Binary Field, So how can I use DRF serializer to save the field value
I have referred the documentation https://www.django-rest-framework.org/api-guide/fields/#custom-fields and understood some of the part and created below, but I'm not sure how to use it in serializer
Model
class MyData(models.Model):
data = models.BinaryField()
Custom Field
class BinaryField(serializers.Field):
def to_representation(self, value):
return value.decode('utf-8')
def to_internal_value(self, value):
return value.encode('utf-8')
But how should I use this in my below serializer
class BlobDataSerializer (serializers.ModelSerializer):
class Meta:
model = MyData
fields = ('id', 'data')
So basically I'm trying to store incoming data in binary field. Thanks in advance
Like this:
class BlobDataSerializer (serializers.ModelSerializer):
class Meta:
model = MyData
fields = ('id', 'data')
data = BinaryField()
For a more reusable solution, you could also subclass ModelSerializer and customize the serializer_field_mapping.
See https://www.django-rest-framework.org/api-guide/serializers/#customizing-field-mappings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With