Search code examples
djangodjango-rest-frameworkdjango-model-field

How do I take input as String and save as Binary in Django using Django REST Framework?


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?


Solution

  • 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.