On Tue, Jul 11, 2017 at 12:05 AM, Mike Morris <
mi...@musicplace.com> wrote:
> From your description (save a SHA-256 checksum), you do not need a binary
> field. Binaries are always of indeterminant length; they can hold photos,
> executables, sound files, etc.
>
> By definition, a SHA -256 is 256 bytes of ASCII.
>
> You probably want a CharField(length=256).
>
BinaryField is arbitrary size, binaries are not. The binary
representation of a SHA-256 is significantly smaller (it's 256 *bits*,
or 32 bytes), hence why the OP wants to store his binary objects in
the most efficient format possible, not 2 or 8 times that size.
Its like storing an IPv4 address as the 15 bytes string
"10.123.132.254" or the 4 byte integer 175867134.
Guido:
You can make your own custom database types quite simply (completely untested):
class FixedSizedBinaryField(models.BinaryField):
def __init__(self, num_bytes=None, *args, **kwargs):
self.nbytes = num_bytes
super(FixedSizedBinaryField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(FixedSizedBinaryField, self).deconstruct()
kwargs[''num_bytes'] = self.nbytes
return name, path, args, kwargs
def db_type(self, connection):
return "binary(%d)" % self.nbytes
For more details, check out the docs on custom fields:
https://docs.djangoproject.com/en/1.11/howto/custom-model-fields/
Cheers
Tom