[Django]-Django small bytestrings on model, what type should be used for modelling?

3đź‘Ť

âś…

BinaryField is the right choice for this—as of Django 2.1. You’re unfortunately right that before that the documentation contains a caveat about “it is not possible to filter a queryset on a BinaryField value”. Given that you were able to do just that, you might want to investigate and see exactly what the limitations are here.

Passing a plain bytestring to a CharField is definitely wrong. Django will implicitly convert your byte string to Unicode before encoding it for the database, and that will create errors. For example, there are byte sequences that are not valid utf-8 representations: try Foobar.objects.create(charfield=b'\xf8').

Another option is to explicitly encode the bytefield yourself (into hex characters, say), probably by making a custom field. But then you have to do the same thing whenever you filter(). Ugly.

So try to make BinaryField work.

Leave a comment