BinaryField value type differs across databases

I was using BinaryField that according to the docs can be assigned bytes, bytearray and memoryview but the docs make no mention of the value type you get back from the database.

I tested with SQlite and the field returned bytes but someone else used my project with Postgres where BinaryField returns a memoryview. Unfortunately, that was incompatible with how the value was used later in the code.

Should the return type be unified? Or is this an opportunity for improved documentation around the types that BinaryField can return depending on the database?

Unification discussions aside, it’s a non-trivial effort to document how each of the individual databases (multiply that by the drivers for that database) behave which is usually agreed to be out of scope of the Django documentation.

Maybe then at least provide a hint that the resulting type is database dependent. I feel like otherwise it’s quite the gotcha.

There is an existing ticket tracking this exact behaviour difference between Postgres and SQLite.

It’d be interesting to confirm if the returned type changed on psycopg>=3 and what is returned on mysqlclient and Oracle backends to determine which is one is the outlier here.

1 Like

@charettes Your assumption is correct, psycopg (3) does return bytes now: psycopg release notes - psycopg 3.2.0.dev1 documentation

I just did a quick test with mysqlclient and it also returns bytes.

Thanks for the sleuthing David!

In this case we might just want to wont-fix the ticket and document it as an oddity of psycopg<3.0.17

1 Like