On Thursday, July 13, 2017 at 4:06:38 PM UTC+2, Tom Evans wrote:
 [...]

> 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/ 
>

Thanks for the suggestion. I am now working with this custom field class (I 
actually found the relevant documentation and the solution myself in the 
meantime. It's almost identical to yours, except without a configurable 
length):

class SHA256Field(models.BinaryField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 32
        super(SHA256Field, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(SHA256Field, self).deconstruct()
        del kwargs["max_length"]
        return name, path, args, kwargs

    def db_type(self, connection):
        return "BINARY(32)"

This works very well for me - in MySQL/MariaDB. I haven't tested it with 
any other database systems.

Regards,

Guido
 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/15f8406e-998f-4822-8afe-a636f8699177%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to