简体   繁体   中英

Add Binary data into django rest framework API

model.py

class TblSnapshot(models.Model):
    url = models.CharField(max_length=500)
    snapshot = models.BinaryField()

I want to add Binary Data in API, but it's generating error

TypeError at /api
__str__ returned non-string (type memoryview)

You'll need to implement a custom field ( as per here) . This is how your serializer would look for such model

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')

class TblSnapshotSerializer(serializers.ModelSerializer):
    class Meta:
        model = TblSnapshot
        fields = ('id', 'url', 'snapshot')

    snapshot = BinaryField()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM