2

Here is my model:

class Example(models.Model):
    file = S3PrivateFileField()
    text = models.TextField(null=True, blank=True)
    binary = models.BinaryField(null=True, blank=True)

and here is the serializer:

class ExampleSerializer(ModelSerializer):

    class Meta:
        model = Example
        fields = ['file', 'text', 'binary']

First of all, in the Browsable API, I can see the file and text fields but not the binary fields. How do I see that field?

Secondly, the input data type for the binary field is string and I would like to save it as binary data in the database. How can I get it to work?

Rafi
  • 467
  • 6
  • 17

1 Answers1

2

To convert a str to a byte string, encode it:

>>> s = 'hello'
>>> b = s.encode()  # default is UTF-8 encoding
>>> b
b'hello'

You probably cannot see the BinaryField in the UI because it has no default widget. In older versions of Django, BinaryFields weren't even editable, since they are generally used to store raw data, including characters not included in ASCII.

Greg Schmit
  • 4,275
  • 2
  • 21
  • 36
  • Thank you for your suggestion. For some reason, it did not work for me. `string = self.request.data['binary']` `self.request.data['binary'] = ''.join(format(i, 'b') for i in bytearray(string, encoding='utf-8'))` This worked for the conversion but I am still getting an error while I am trying to save the data. – Rafi Oct 08 '19 at 16:45
  • Yeah don't do that. You're making a string representation of binary data. That's bad, mmkay? Are you trying to have the user input literal 0s and 1s? That's not what a binary field is meant to be. You need to ask a new question and be real clear on what you actually want. – Greg Schmit Oct 08 '19 at 16:59
  • Ok, I was able to save the data into the database using your original solution. You are right! Thanks! – Rafi Oct 08 '19 at 17:02