0

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)
1
  • 3
    Can you post the full traceback and the code for your serializer? Commented Jan 9, 2020 at 8:32

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

it's giving error of 'Tblsnapshot' object has no attribute 'decode' @Jura- brazdil
Seems like the serializer gets a whole TblSnapshot objects into its snapshot field. It's tblsnapshot.snapshot that is the binary value and has the decode method. Can you post your view?
actually I am using primary key of Tblsnapshot from another table as a foreign key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.