Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DRF Custom serializer field with DB model

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 image 745
pab789 Avatar asked Oct 31 '25 03:10

pab789


1 Answers

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

like image 143
Nico Griffioen Avatar answered Nov 01 '25 16:11

Nico Griffioen